我有这个对象数组,我需要通过name属性进行分组,我需要一个新数组来汇总所有具有相同名称的对象。
0:{id: 2, percent: "0.5968877829730651%", barGraphClass: "background-orange", labelClass: "background-orange", name: "cadastro pendente", …}
1:{id: 4, percent: "0.8286446806061278%", barGraphClass: "background-orange", labelClass: "background-orange", name: "cadastro pendente", …}
2:{id: 1, percent: "95.64138595007097%", barGraphClass: "background-toal", labelClass: "background-toal", name: "GTINs em uso", …}
3:{id: 3, percent: "2.1742168007401386%", barGraphClass: "background-orange", labelClass: "background-orange", name: "cadastro pendente", …}
4:{id: 5, percent: "0.1384810669784176%", barGraphClass: "background-orange", labelClass: "background-orange", name: "cadastro pendente", …}
5:{id: 6, percent: "0.2222506510683319%", barGraphClass: "background-orange", labelClass: "background-orange", name: "cadastro pendente", …}
6:{id: 7, percent: "0.39811621251585005%", barGraphClass: "background-orange", labelClass: "background-orange", name: "cadastro pendente", …}
7:{id: 8, percent: "0.000016855047100586368%", barGraphClass: "background-peach", labelClass: "background-peach", name: "GTINs bloqueados", …}
我试过的是const grouped = _.groupBy(newArray, 'name');
它按名称分组,但它没有总结值,只创建3个separeate数组并保持相等的值
答案 0 :(得分:2)
您可以使用.map和.Sumby
var data = [
{
"id": 2,
"percent": 0.5968877829730651,
"barGraphClass": "background-orange",
"labelClass": "background-orange",
"name": "cadastro pendente"
},
{
"id": 4,
"percent": 0.8286446806061278,
"barGraphClass": "background-orange",
"labelClass": "background-orange",
"name": "cadastro pendente"
},
{
"id": 1,
"percent": 95.64138595007097,
"barGraphClass": "background-toal",
"labelClass": "background-toal",
"name": "GTINs em uso"
}
]
const ans = _(data)
.groupBy('name')
.map((name, id) => ({
name: id,
payout: _.sumBy(name, 'percent')
}))
.value()
console.log(ans);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>