从对象数组中减少javascript对象

时间:2018-06-12 17:54:01

标签: javascript

我有一个像这样的对象数组:

[{duration: 12, place: 3}, {duration: 21, place: 4}, {duration: 22, place: 3}]

我想结合来自同一地方值的所有持续时间。 如何在javascript中编写一个函数,可以给我这样的输出?

[{duration: 34, place: 3}, {duration: 21, place: 4}]

1 个答案:

答案 0 :(得分:1)

另一种方法是使用函数const array = [{duration: 12, place: 3}, {duration: 21, place: 4}, {duration: 22, place: 3}], result = Object.values(array.reduce((a, {duration, place}) => { (a[place] || (a[place] = {duration: 0, place})).duration += duration; return a; }, {})); console.log(result);对具有相同位置值的对象进行分组。



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

ko.applyBindings({ Orders: this.Orders }, document.getElementById('oTable'));