使用lodash或underscore.js在javascript中处理对象数组

时间:2018-07-23 11:24:46

标签: javascript lodash

我有以下格式的对象数组:

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尝试了一些操作,但未能获得所需的输出。

2 个答案:

答案 0 :(得分:2)

类似:

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>

答案 1 :(得分:1)

您反对使用标准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()方法对累加器和数组中的每个元素(从左到右)应用一个函数,以将其减小为单个值。