javascript - 用对象求和数组

标签 javascript lodash

我有以下包含对象的数组,我想总结所有出现的 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 的数组。值(value)观。但是,我想取回 377 的结果值.有什么建议我做错了吗?

感谢您的回复!

最佳答案

使用纯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>

关于javascript - 用对象求和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50670204/

相关文章:

javascript - Unhandled Promise rejection : push. on is not a function

javascript - 使用 javascript 从 WordPress 页面读取 HTML

javascript - Angular 1.x 无法根据内部逻辑将类添加到自定义指令

typescript - 错误 TS2365 : Operator '+' cannot be applied to types '{}' and 'number'

javascript - AngularJS 应用程序中 _.find Lodash 语句内的大括号

javascript - 当 li 位于 Jquery 中列表项的子级别时,如何在 li 中获取空 ol?

javascript - 如何获取对象数组的某些部分作为新数组?

javascript - 如何使用 javascript 或 lodash 获取 Uniq 对象

javascript - 如何使用lodash从bigArray中删除smallArray中的所有项目?

javascript - div onclick 不触发(css 动画箭头,可能的 div 大小/覆盖问题)