【问题标题】:I need to reverse the formatting of an object我需要反转对象的格式
【发布时间】:2019-09-07 17:33:24
【问题描述】:

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

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

这是我的代码:

//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
  }

【问题讨论】:

    标签: javascript arrays function object


    【解决方案1】:

    你不应该在循环中返回,否则它只会返回一个键而不是完成执行,你可以填充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);

    【讨论】:

    • 非常感谢您澄清 + 键。现在一切都变得更有意义了。我希望我有更多 6 个帐户来为你投票更多。
    【解决方案2】:

    这是使用Object.entries()Array#reduce() 的另一种方法

    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']
    };
    
    
    const transform = (o) =>  Object.entries(o)
        .reduce((acc, [k, arr]) => arr.reduce((a, el) => (a[el.toLowerCase()] = k, a), acc), {});
    
    
    console.log(transform(oldScoreKey))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      相关资源
      最近更新 更多