簡體   English   中英

將對象數組中的對象屬性總結為單個對象Lodash

[英]sum up object properties in array of objects into a single object Lodash

我一直在努力做到這一點並且遇到了問題,所以我應該向ppl詢問更多經驗。 我有一個對象數組,可以說是被稱為項目,我需要總結數組中不同對象的一些屬性,並在最后總結它們。 用戶可以進行一些選擇,我只需要總結他們給我的數組中所選擇的屬性,所以我想也許可以在lodash中使用_.pick函數。 如果可能的話,我想在一個循環中這樣做,因為items數組最多可以有1000個項目。 這是一個例子:

var items = [
{'lightBlue':4, 'darkBlue':2, 'red':4, 'orange':6, 'purple':7},
{'lightBlue':6, 'darkBlue':5, 'red':1, 'orange':2, 'purple':3},
{'lightBlue':2, 'darkBlue':4, 'red':3, 'orange':4, 'purple':9}
]

var userSelectedColors = ['lightBlue', 'darkBlue'];

我想看到的是所有藍色的總結如下:

var summedUp = [{'lightBlue':12, 'darkBlue':11}];

然后總結結果得到總數

var totalCount = 23

什么是最好的和高效的方式來獲得這個lodash。 userSelectedColors數組可以是1或任何顏色組合。

請提供一個例子,謝謝你的幫助贊賞!

使用_.sumBy

var totalCount = _.sumBy(userSelectedColors, _.partial(_.sumBy, items));

 var items = [ { 'lightBlue': 4, 'darkBlue': 2, 'red': 4, 'orange': 6, 'purple': 7 }, { 'lightBlue': 6, 'darkBlue': 5, 'red': 1, 'orange': 2, 'purple': 3 }, { 'lightBlue': 2, 'darkBlue': 4, 'red': 3, 'orange': 4, 'purple': 9 } ], userSelectedColors = ['lightBlue', 'darkBlue']; var totalCount = _.sumBy(userSelectedColors, _.partial(_.sumBy, items)); console.log(totalCount); 
 <script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script> 

擴展,看起來像:

var totalCount = _.sumBy(userSelectedColors, function(prop) {
    return _.sumBy(items, prop);
});

如果沒有Lodash,更高效的解決方案將是這樣的:

var totalCount = items.reduce(function(total, obj) {
    return total + userSelectedColors.reduce(function(total, prop) {
        return total + obj[prop];
    }, 0);
}, 0);

 var items = [ { 'lightBlue': 4, 'darkBlue': 2, 'red': 4, 'orange': 6, 'purple': 7 }, { 'lightBlue': 6, 'darkBlue': 5, 'red': 1, 'orange': 2, 'purple': 3 }, { 'lightBlue': 2, 'darkBlue': 4, 'red': 3, 'orange': 4, 'purple': 9 } ], userSelectedColors = ['lightBlue', 'darkBlue']; var totalCount = items.reduce(function(total, obj) { return total + userSelectedColors.reduce(function(total, prop) { return total + obj[prop]; }, 0); }, 0); console.log(totalCount); 
 <script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script> 

在效率方面,我認為這很難被擊敗,因為它只在陣列中迭代一次,但它並不像@ 4castle那樣簡單。 (另外,只有1000件商品,你永遠不會注意到性能差異。)

var items = [
    {'lightBlue':4, 'darkBlue':2, 'red':4, 'orange':6, 'purple':7},
    {'lightBlue':6, 'darkBlue':5, 'red':1, 'orange':2, 'purple':3},
    {'lightBlue':2, 'darkBlue':4, 'red':3, 'orange':4, 'purple':9}
]

var userSelectedColors = ['lightBlue', 'darkBlue'];

var sums = {};

_.each(items, function (item) {
    _.each(userSelectedColors, function (color) {
        sums[color] = (sums[color] || 0) + item[color];
    });
});

console.log('Summary: ', sums);

console.log('Grand total: ', _.sum(_.values(sums)));

輸出:

Summary:  { lightBlue: 12, darkBlue: 11 }
Grand total:  23

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM