如何通过对象键对对象数组进行分组,以根据分组创建新的对象数组?
例如,我有一系列汽车对象:
const array = [
{red: [ {height: 50} ]},
{green: [ {height: 20} ]},
{blue: [ {height: 30} ]},
{blue: [ {height: 40} ]},
{red: [ {height: 10} ]},
{green: [ {height: 60} ]}
]
我想创建一个新的对象数组。(关键是颜色)
const result = [
{red: [{height: 50}, {height: 10}]},
{green: [{height: 20}, {height: 60}]},
{blue: [{height: 30}, {height: 40}]}
]
我尝试使用 lodash.groupBy,但我根本不知道如何解决这个问题。
使用数组reduce您可以迭代数据并计算结果对象。
const array = [
{ 'red': [ { height: 50 } ] },
{ 'green': [ { height: 20 } ] },
{ 'blue': [ { height: 30 } ] },
{ 'blue': [ { height: 40 } ] },
{ 'red': [ { height: 10 } ] },
{ 'green': [ { height: 60 } ] }
];
const res = array.reduce((acc, element) => {
// Extract key and height value array
const [key, heightValue] = Object.entries(element)[0];
// Get or create if non-exist, and push height value from array, index 0
(acc[key] || (acc[key] = [])).push(heightValue[0]);
return acc;
}, {});
console.log(res);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)