簡體   English   中英

使用lodash或underscore.js在javascript中處理對象數組

[英]Manipulation of array of objects in javascript using lodash or underscore.js

我有以下格式的對象數組:

data= [ { 'a': [{"_id":"aa","type":"credit","amount":500}]},
        { 'b': [{"_id":"ba","type":"credit","amount":600},
                {"_id":"bb","type":"refund","amount":200}]},
        { 'a': [{"_id":"aaa","type":"credit","amount":600},
                {"_id":"aab","type":"credit","amount":200}]}]

我要做的就是達到這樣的目標:

result=[ { 'a': 500 },{ 'b': 600},{ 'a': 800} ]

這基本上是將沒有類型退款的對象的金額字段加起來。

我用lodash的_.reject和_.sumBy嘗試了一些操作,但未獲得所需的輸出。

就像是:

 const data = [{'a':[{"_id":"aa","type":"credit","amount":500}]},{'b':[{"_id":"ba","type":"credit","amount":600},{"_id":"bb","type":"refund","amount":200}]}] const sum = (items) => _.chain(items) .reject({ type: 'refund' }) .sumBy('amount') .value(); const res = _.map(data, item => _.mapValues(item, sum)); console.log(res) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script> 

您反對使用標准javascript嗎?

在此示例中,我使用map遍歷數組的每個部分並reduce總和。

 const objs = [{'a':[{"_id":"aa","type":"credit","amount":500}]},{'b':[{"_id":"ba","type":"credit","amount":600},{"_id":"bb","type":"refund","amount":200}]}] let newObjs = objs.map((o) => { let key = Object.keys(o)[0]; let amount = o[key].length > 1 ? o[key].reduce((a, b) => { return { amount: a.amount + (b.type == "refund" ? 0 : b.amount) } }).amount : o[key][0].type == "refund" ? 0 : o[key][0].amount; return JSON.parse(`{"${key}":${amount}}`) }) console.log(newObjs) 


map()方法創建一個新數組,並在調用數組中的每個元素上調用提供的函數。


reduce()方法對一個累加器和數組中的每個元素(從左到右)應用一個函數,以將其減小為單個值。


暫無
暫無

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

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