[英]How to group by and sum an array of objects javascript?
const array = [
{
"data": {
"qty": "5",
"toy": {
"id": 3,
},
"available": "yes",
}
},
{
"data": {
"qty": "5",
"toy": {
"id": 10,
},
"available": "no"
}
},
{
"data": {
"qty": "59",
"toy": {
"id": 10,
},
"available": "yes",
}
},
{
"data": {
"qty": "5",
"toy": {
"id": 3,
},
"available": "yes",
}
}
]
var result = [];
array.reduce(function(res, value) {
if (!res['data']['toy'] || !res['data']['toy']['data']) {
res['data'] = {...value['data'] };
result.push(res['data'])
}
if (res['data']['available'] === value['data']['available'] && res['data']['toy']['id'] === value['data']['toy']['id']) {
res['data']['qty'] = parseInt(res['data']['qty']) + parseInt(value['data'].qty)
}
return res;
}, {'data': {}});
console.log(result)
I am working on a js project and I need a bit of help here.我正在做一个 js 项目,在这里我需要一些帮助。 From the array, How to get a new array that has qty as the sum of the other qty value which data.toy.id and available same.
从数组中,如何获得一个新数组,其中 qty 作为 data.toy.id 和可用的其他 qty 值的总和。 ie I want the below array.
即我想要下面的数组。 My code is not working as excepted.
我的代码无法正常工作。 Changes to the same or new code are also fine.
更改相同或新代码也可以。 Thank you.
谢谢你。
const array = [
{
"data": {
"qty": "10",
"toy": {
"id": 3,
},
"available": "yes",
}
},
{
"data": {
"qty": "5",
"toy": {
"id": 10,
},
"available": "no"
}
},
{
"data": {
"qty": "59",
"toy": {
"id": 10,
},
"available": "yes",
}
}
]
You group the array into an object, where the keys are concatenation of available
and id
properties and finally transform the object back to an array using Object.values
.您将数组分组为一个对象,其中键是
available
属性和id
属性的串联,最后使用Object.values
将对象转换回数组。
const array = [ { data: { qty: "5", toy: { id: 3 }, available: "yes" } }, { data: { qty: "5", toy: { id: 10 }, available: "no" } }, { data: { qty: "59", toy: { id: 10 }, available: "yes" } }, { data: { qty: "5", toy: { id: 3 }, available: "yes" } }, ], result = Object.values( array.reduce((r, { data }) => { const k = data.available + data.toy.id; if (r[k]) { r[k].data.qty = String(Number(r[k].data.qty) + Number(data.qty)); } else { r[k] = { data }; } return r; }, {}) ); console.log(result);
You can use Array#reduce() to create arrayHash
object using as keys: ${c.data.toy.id}-${c.data.available}
您可以使用Array#reduce()作为键创建
arrayHash
对象: ${c.data.toy.id}-${c.data.available}
Code:代码:
const array = [{data: {qty: '5',toy: {id: 3,},available: 'yes',},},{data: {qty: '5',toy: {id: 10,},available: 'no',},},{data: {qty: '59',toy: {id: 10,},available: 'yes',},},{data: {qty: '5',toy: {id: 3,},available: 'yes',},},] const arrayHash = array.reduce((a, { data }) => { const key = `${data.toy.id}-${data.available}` a[key] = a[key] || { data: { ...data, qty: 0 } } a[key].data.qty = (+a[key].data.qty + +data.qty).toString(); return a }, {}) const result = Object.values(arrayHash) console.log(result)
I'd suggest using Array.reduce()
to group by a key
, which will be combined value of the toy id and the available property.我建议使用
Array.reduce()
按key
分组,这将是玩具 id 和可用属性的组合值。
We'd create a map of all toys based on this key, summing the quantity for each.我们将根据这个键创建所有玩具的地图,将每个玩具的数量相加。
Finally, we'll use Object.values()
to convert back into an array.最后,我们将使用
Object.values()
转换回数组。
const array = [ { "data": { "qty": "5", "toy": { "id": 3, }, "available": "yes", } }, { "data": { "qty": "5", "toy": { "id": 10, }, "available": "no" } }, { "data": { "qty": "59", "toy": { "id": 10, }, "available": "yes", } }, { "data": { "qty": "5", "toy": { "id": 3, }, "available": "yes", } } ]; const result = Object.values(array.reduce((acc, { data: { qty, toy, available } }) => { const key = `${toy.id}-${available}`; acc[key] = acc[key] || { data: { qty: 0, toy, available } }; acc[key].data.qty += Number(qty); return acc; }, {})) console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }
I'd use just reduce我会用减少
const a1 = [ { "data": { "qty": "5", "toy": { "id": 3, }, "available": "yes", } }, { "data": { "qty": "5", "toy": { "id": 10, }, "available": "no" } }, { "data": { "qty": "59", "toy": { "id": 10, }, "available": "yes", } }, { "data": { "qty": "5", "toy": { "id": 3, }, "available": "yes", } } ] const a2 = a1.reduce((acc, it) => { let found = acc.find( dp => dp.data.toy.id === it.data.toy.id && dp.data.available === it.data.available ) if(found){ found.data.qty = ( Number(found.data.qty) + Number(it.data.qty) ).toString() } else acc.push(it) return acc }, []) console.log(JSON.stringify(a2, null,2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.