用对象求和数组

时间:2018-06-03 19:28:04

标签: 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值。但是,我想取回377的结果值。有什么建议我做错了吗?

感谢您的回复!

4 个答案:

答案 0 :(得分:3)

使用普通的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>

答案 1 :(得分:1)

只需使用一个_.sumBy对象数组和所需的键watt进行求和。

您的尝试使用的是对象,而不是_.sumBy的数组。该对象不是数组,返回值为零。

var 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 }],
    getWatt = _.sumBy(allProducts, 'watt');

console.log(getWatt)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

答案 2 :(得分:1)

尝试以下方法:

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
  }
];

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

答案 3 :(得分:1)

我已经阅读了答案,但我想为您的问题添加一个解释。你获得数组的原因是因为使用了.map。当map返回时,数组不是单个元素。此外,您希望将返回的数组修改为map并不这样做。

您尝试实现的目标可以使用.reduce完成。我的意思是.reduce存在的原因

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
  }
];
var getWatt = allProducts.reduce((acc,curr)=> acc + curr.watt,0);
console.log(getWatt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>