通过匹配键/值对重新组合对象数组

时间:2019-03-03 01:16:20

标签: javascript

是否有快速或推荐的动态函数来重新组合javascript中的对象数组?例如,如果我想按一个键分组,并在新对象中所有第二个键值的第二个键中创建一个数组。还假设颜色数量没有尽头,因此新的数组位置必须是动态的,我们不一定要假设它是动态的。下面的示例:

从此

array = [
    {color:"red", number:23},
    {color:"blue", number:52},
    {color:"green", number:55},
    {color:"red", number:15},
    {color:"green", number:53},
    {color:"blue", number:23},
    {color:"red", number:25},
]

对此

array = [
    {color:"red", numbers:[23,15,25]},
    {color:"blue", numbers:[52,23]},
    {color:"green", numbers:[55,53]}
]

1 个答案:

答案 0 :(得分:2)

您可以使用函数reduce对值进行分组,并使用函数Object.values提取分组的值。

let array = [    {color:"red", number:23},    {color:"blue", number:52},    {color:"green", number:55},    {color:"red", number:15},    {color:"green", number:53},    {color:"blue", number:23},    {color:"red", number:25}],
    result = Object.values(array.reduce((a, {color, number}) => {
      (a[color] || (a[color] = {color, numbers: []})).numbers.push(number);
      return a;
    }, Object.create(null)));

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