如果您能帮助我解决有关嵌套 JavaScript 对象的问题,我将不胜感激。我想通过在嵌套对象“objToBeSumUp”中按类别总结两个值(价格和数量)来创建一个新对象。同时求和两个值是如此困难,至少我可以创建 for 循环来求和一个值,如下面我的中途代码中所述。
此外,我们希望按总价格降序对对象进行排序。
要总结的对象:
const objToBeSumUp ={
0: {
value: {
category:{
value: a
},
price:{
value: 500
},
quantity:{
value: 5
}
}
},
1: {
value: {
category:{
value: a
},
price:{
value: 300
},
quantity:{
value: 3
}
}
},
2: {
value: {
category:{
value: b
},
price:{
value: 800
},
quantity:{
value: 8
}
}
},
3: {
value: {
category:{
value: b
},
price:{
value: 400
},
quantity:{
value: 4
}
}
}
}
预期对象:
const objExpected = {
0: {
value: {
category:{
value: b
},
totalPrice:{
value: 1200
},
totalQuantity:{
value: 12
}
}
},
1: {
value: {
category:{
value: a
},
totalPrice:{
value: 800
},
totalQuantity:{
value: 8
}
}
},
};
我的中途代码:
const objExpected = {};
for (let i = 0; i < objToBeSumUp.length; i++) {
const category = objToBeSumUp[i].value['category'].value;
if (!objExpected[category]) {
objExpected[category] = 0;
}
// Summing prices up
const price = objToBeSumUp[i].value['price'].value;
objExpected[category] += parseInt(price)
您可以按总价格降序对数组进行排序。
将排序后的数组缩减回预期的对象格式,保留排序步骤中的顺序。
你应该已经以预期的格式总结了 OBJ
注:
console.log(JSON.stringify(objExpected, null, 2));
用于在控制台中正确显示对象,因为使用常规 console.log(objExpected) 您可能会看到输出:
类别:[对象]
价格:[对象]
const objToBeSumUp = {
0: {
value: {
category: { value: 'a' },
price: { value: 500 },
quantity: { value: 5 }
}
},
1: {
value: {
category: { value: 'a' },
price: { value: 300 },
quantity: { value: 3 }
}
},
2: {
value: {
category: { value: 'b' },
price: { value: 800 },
quantity: { value: 8 }
}
},
3: {
value: {
category: { value: 'b' },
price: { value: 400 },
quantity: { value: 4 }
}
}
};
const summedValues = {};
// Summing up prices and quantities by category
Object.values(objToBeSumUp).forEach(item => {
const category = item.value.category.value;
const price = item.value.price.value;
const quantity = item.value.quantity.value;
if (!summedValues[category]) {
summedValues[category] = { totalPrice: 0, totalQuantity: 0 };
}
summedValues[category].totalPrice += price;
summedValues[category].totalQuantity += quantity;
});
// Convert summedValues object to an array, sort by totalPrice, and convert back to the expected object format
const sortedArray = Object.entries(summedValues).sort((a, b) => b[1].totalPrice - a[1].totalPrice);
const objExpected = sortedArray.reduce((acc, [category, { totalPrice, totalQuantity }], index) => {
acc[index] = {
value: {
category: { value: category },
totalPrice: { value: totalPrice },
totalQuantity: { value: totalQuantity }
}
};
return acc;
}, {});
console.log(JSON.stringify(objExpected, null, 2));