用对象总结数组 [英] Sum up array with objects

查看:60
本文介绍了用对象总结数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将对象与以下数组组合在一起,我想总结所有出现的watt:

I am having the following array with objects and I would like to sum up all occurrences of watt:

let allProducts = [{
    "unique_id": "102",
    "currency": "$",
    "price": "529.99",
    "watt": 150
  },
  {
    "unique_id": "11",
    "currency": "$",
    "price": "323",
    "watt": 150
  },
  {
    "unique_id": "13",
    "currency": "$",
    "price": "23",
    "watt": 77
  }
]

let getWatt =
  _(allProducts)
  .map((objs, key) => ({
    'watt': _.sumBy(objs, 'watt')
  }))
  .value()

console.log(getWatt)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

如您所见,我返回了一个0值数组.但是,我想取回377的结果值.有什么建议我做错了吗?

As you can see I get back an array of 0 values. However, I would like to get back the result value of 377. Any suggestions what I am doing wrong?

感谢您的答复!

推荐答案

使用普通js很容易

const sum = allProducts.reduce((a, {watt}) => a + watt, 0);
console.log(sum);

<script>
let allProducts = [{
    "unique_id": "102",
    "currency": "$",
    "price": "529.99",
    "watt": 150
  },
  {
    "unique_id": "11",
    "currency": "$",
    "price": "323",
    "watt": 150
  },
  {
    "unique_id": "13",
    "currency": "$",
    "price": "23",
    "watt": 77
  }
]


</script>

这篇关于用对象总结数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆