如何从数组创建键值对?

时间:2020-08-19 20:21:28

标签: javascript node.js arrays dictionary

我有一个包含以下数据的数组对象:

const arr = [
{
  key: 'mykey1597855209',
  integrity: 'sha512-T9JWj=='
},
{
  key: 'mykey159785520915978552101597855212',
  integrity: 'sha512-T9JWj=='
},
{
  key: 'mykey15978552091597855210',
  integrity: 'sha512-lcddfd=='
},
{
  key: 'otherkey15978552091597855210',
  integrity: 'sha512-abcdfd=='
}];

我想从key对象创建value arr[]对,以使integrity成为键而key成为值

所需的输出如下:

{
  "sha512-T9JWj==": [
    "mykey1597855209",
    "mykey159785520915978552101597855212"
  ],
  "sha512-lcddfd==": [
    "mykey15978552091597855210"
  ],
  "sha512-abcdfd==": [
    "otherkey15978552091597855210"
  ]
}

我写了以下代码:

const arr = [{
    key: 'mykey1597855209',
    integrity: 'sha512-T9JWj=='
  },
  {
    key: 'mykey159785520915978552101597855212',
    integrity: 'sha512-T9JWj=='
  },
  {
    key: 'mykey15978552091597855210',
    integrity: 'sha512-lcddfd=='
  },
  {
    key: 'otherkey15978552091597855210',
    integrity: 'sha512-abcdfd=='
  }
];
const result = Object.assign(...arr.map(a => ({
  [a.integrity]: a.key
})));

console.log(result)

3 个答案:

答案 0 :(得分:1)

您可以像这样转换它:

 _user_id |   _name    |   _avatar   |   _banner   | _total_events |   _total_by_game    
 ----------+------------+-------------+-------------+---------------+---------------------
          1 | test1login | avatar1.png | banner1.png |          3 | {"cs": 2, "lol": 1}
          2 | test2login | avatar2.png | banner2.png |          1 | {"cs": 0, "lol": 1}

答案 1 :(得分:1)

您可以使用Object.fromEntries

const arr = [{key: 'mykey1597855209',integrity: 'sha512-T9JWj=='},{key: 'mykey159785520915978552101597855212',integrity: 'sha512-T9JWj=='},{key: 'mykey15978552091597855210',integrity: 'sha512-lcddfd=='},{key: 'otherkey15978552091597855210',integrity: 'sha512-abcdfd=='}];

let map = Object.fromEntries(arr.map(({_, integrity }) => [integrity, []]));
arr.forEach(({key, integrity}) => map[integrity].push(key));

console.log(map);

reduce

const arr = [{key: 'mykey1597855209',integrity: 'sha512-T9JWj=='},{key: 'mykey159785520915978552101597855212',integrity: 'sha512-T9JWj=='},{key: 'mykey15978552091597855210',integrity: 'sha512-lcddfd=='},{key: 'otherkey15978552091597855210',integrity: 'sha512-abcdfd=='}];

let map = arr.reduce((acc, { key, integrity }) => {
  acc[integrity] = acc[integrity] || [];
  acc[integrity].push(key);
  return acc;
}, {});

console.log(map);

答案 2 :(得分:1)

arr.reduce((acc, curr) => {    
    acc[curr.integrity] = (acc[curr.integrity]) ? 
                          [ ...acc[curr.integrity], curr.key ] : 
                          [ curr.key ]    
    return acc;
}, {})