我有数组:
[
['a', 'b', 'c'],
['a', 'h', 'k'],
['c', 'd', 'e']
]
有没有最好的方法可以将其转换成这样的对象?
{
a: [
['a', 'b', 'c'],
['a', 'h', 'k'],
],
c: [
['c', 'd', 'e']
]
}
您可以.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] 删除。
我来说两句