将多个对象减少为一个

时间:2018-11-12 14:32:55

标签: javascript reduce

假设我有一个对象数组:

[
    {
        category: 'Category A',
        max: 10,
        min: 12
    },

    {
        category: 'Category B',
        max: 2,
        min: 1
    },

    {
        category: 'Category C',
        max: 4,
        min: 4
    }
]

但是,我似乎无法获得如下所示的数组:

{
    category: 'Category ALL',
    max: 16,
    min: 17
}

我尝试通过reduce进行的所有尝试均无效。

4 个答案:

答案 0 :(得分:2)

您可以通过将对象的最小值和最大值作为下一个迭代的总和来减少数据。

var data = [{ category: 'Category A', max: 10, min: 12 }, { category: 'Category B', max: 2, min: 1 }, { category: 'Category C', max: 4, min: 4 }],
    result = Object.assign(
        { category: 'Category All' }, 
        data.reduce((a, b) => ({ min: a.min + b.min, max: a.max + b.max }))
    );
    
console.log(result);

通过使用数组作为键来实现更动态的方法。

var data = [{ category: 'Category A', max: 10, min: 12 }, { category: 'Category B', max: 2, min: 1 }, { category: 'Category C', max: 4, min: 4 }],
    keys = ['min', 'max'],
    result = Object.assign(
        { category: 'Category All' }, 
        data.reduce((a, b) => Object.assign(...keys.map(k => ({ [k]: a[k] + b[k] }))))
    );
    
console.log(result);

答案 1 :(得分:1)

var array = [{
    category: 'Category A',
    max: 10,
    min: 12
  },

  {
    category: 'Category B',
    max: 2,
    min: 1
  },

  {
    category: 'Category C',
    max: 4,
    min: 4
  }
]

var result = array.reduce((a, v) => {
  a.max += v.max
  a.min += v.min
  return a
}, {
  category: "Category All",
  max: 0,
  min: 0
})

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

答案 2 :(得分:0)

只需将初始对象{ category: 'Category ALL', max: 0, min: 0 }传递到reduce,对于每个项目,只需将其maxmin添加到该对象即可:

let result = array.reduce((acc, obj) => {
    acc.max += obj.max;
    acc.min += obj.min;
    return acc;
}, { category: 'Category ALL', max: 0, min: 0 });

示例:

let array = [{ category: 'Category A', max: 10, min: 12 }, { category: 'Category B', max: 2, min: 1 }, { category: 'Category C', max: 4, min: 4 }];

let result = array.reduce((acc, obj) => {
    acc.max += obj.max;
    acc.min += obj.min;
    return acc;
}, { category: 'Category ALL', max: 0, min: 0 });

console.log(result);

答案 3 :(得分:0)

您可以使用Array.reduce,以便将对象数组简化为单个对象,而使用es6则可以在一行中编写。

请参见下面的代码,希望它可以解决问题

var res = [
    {
        category: 'Category A',
        max: 10,
        min: 12
    },

    {
        category: 'Category B',
        max: 2,
        min: 1
    },

    {
        category: 'Category C',
        max: 4,
        min: 4
    }
]

var result = res.reduce((a,c) =>  ({category:"Category All", max: a.max + c.max, min: a.min + c.min}))

console.log("result", result)