我有一个像这样的对象数组:
[{duration: 12, place: 3}, {duration: 21, place: 4}, {duration: 22, place: 3}]
我想结合来自同一地方值的所有持续时间。 如何在javascript中编写一个函数,可以给我这样的输出?
[{duration: 34, place: 3}, {duration: 21, place: 4}]
答案 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'));