Javascript:将数组转换为对象

基安·托安(Kieu Toan)

我有数组:

[
  ['a', 'b', 'c'],
  ['a', 'h', 'k'],
  ['c', 'd', 'e']
]

有没有最好的方法可以将其转换成这样的对象?

{
  a: [
       ['a', 'b', 'c'],
       ['a', 'h', 'k'],
     ],
  c: [
       ['c', 'd', 'e']
     ]
}
穆罕默德·乌斯曼(Mohammad Usman)

您可以.reduce()用来获取所需的输出:

const data = [
  ['a', 'b', 'c'],
  ['a', 'h', 'k'],
  ['c', 'd', 'e']
];

const result = data.reduce((r, c) => {
  r[c[0]] = r[c[0]] || [];
  r[c[0]].push(c);
  return r;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章