首页 > 解决方案 > 我需要反转对象的格式

问题描述

我在下面有这个对象,我需要使用函数transform(oldScoreKey)来重新格式化对象,所以字母是键,数字是值。

我知道如何使用for循环内的for...in循环迭代对象内的每个字母,但我不明白我应该如何让函数对对象本身进行实际的重新格式化。

这是我的代码:

//here is the oldScoreKey

const oldScoreKey = {
   1: ['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'],
   2: ['D', 'G'],
   3: ['B', 'C', 'M', 'P'],
   4: ['F', 'H', 'V', 'W', 'Y'],
   5: ['K'],
   8: ['J', 'X'],
   10: ['Q', 'Z']
};

//here is the basic format of what I have thus far,
//as far as the layout of the transform function 

function transform(obj) {

  const newScorekey = {};

  for (var key in oldScoreKey) {
    for(let i = 0; i < oldScoreKey[key].length; i++) {
      return oldScoreKey[key][i].toLowerCase();
    }
  } return newScorekey;
}

transform(oldScoreKey);



//the final output should be like this, 
//but it doesn't need to be in this exact order, 
//only such that the point values match those in oldScoreKey

const newScorekey = {
    a: 1,
    b: 3,
    c: 3,
    d: 2,
    e: 1,
    f: 4,
    g: 2,
    h: 4,
    i: 1,
    j: 8,
    k: 5,
    l: 1,
    m: 3,
    n: 1,
    o: 1,
    p: 3,
    q: 10,
    r: 1,
    s: 1,
    t: 1,
    u: 1,
    v: 4,
    w: 4,
    x: 8,
    y: 4,
    z: 10
  }

标签: javascriptarraysfunctionobject

解决方案


你不应该在循环中返回,否则它只会返回一个键而不是完成执行,你可以填充newScoreKey对象,并在循环完成时返回:

const oldScoreKey = {
   1: ['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'],
   2: ['D', 'G'],
   3: ['B', 'C', 'M', 'P'],
   4: ['F', 'H', 'V', 'W', 'Y'],
   5: ['K'],
   8: ['J', 'X'],
   10: ['Q', 'Z']
};

function transform(obj) {
  const newScorekey = {};
  for (var key in oldScoreKey) {
    for (let i = 0; i < oldScoreKey[key].length; i++) {
      newScorekey[oldScoreKey[key][i].toLowerCase()] = +key;
    }
  } return newScorekey;
}

newScorekey = transform(oldScoreKey);

console.log(newScorekey);


推荐阅读