[英]Manipulation of array of objects in javascript using lodash or underscore.js
I have an array of object in this format: 我有以下格式的对象数组:
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}]}]
All i want to do is to achieve an object like this: 我要做的就是达到这样的目标:
result=[ { 'a': 500 },{ 'b': 600},{ 'a': 800} ]
This basically adds up the amount field from the objects which does not have a type refund. 这基本上是将没有类型退款的对象的金额字段加起来。
I have tried something with _.reject and _.sumBy of lodash but failed to get the desired output. 我用lodash的_.reject和_.sumBy尝试了一些操作,但未获得所需的输出。
Something like: 就像是:
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>
Are you opposed to using standard javascript? 您反对使用标准javascript吗?
In this example, I use map
to iterate through each part of the array and reduce
to sum the amounts. 在此示例中,我使用
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)
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
map()方法创建一个新数组,并在调用数组中的每个元素上调用提供的函数。
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
reduce()方法对一个累加器和数组中的每个元素(从左到右)应用一个函数,以将其减小为单个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.