gpt4 book ai didi

javascript - 在 Javascript 中解构对象字段并计算总和

转载 作者:行者123 更新时间:2023-11-28 03:39:46 25 4
gpt4 key购买 nike

我无法弄清楚如何解构和添加具有字段的对象的总和。以前我们在对象数组中损坏了单独的对象。现在它们被汇总为 1 个对象,如下所示:

{
"3" {
petIds:{
"113": {"estimatedEats": 10, "owners": {"female":{"kids":1, "adult":2, "senior":10}}, "male":{"kids":1, "adult":2, "senior":10}}
"9": {"estimatedEats": 1, owners: {…}}}

"6":{
petIds:{
"113": {"estimatedEats": 5, "owners": {…}}
"9": {"estimatedEats": 6, "owners": {…}}
"1": {"estimatedEats": 7, "owners": {…}}}
}

以前我可以映射对象数组。我希望最终得到一个如下所示的对象数组:

[{petIds:113, "estimatedEats":15, "owners": (sum of owner description)}...]

有没有办法可以将每个字段转换为对象数组?我认为这样做并映射数组对我来说会更容易。

最佳答案

这应该可以帮助您开始:

var x = {
3:{
petIds:{
113: {estimatedEats: 10, owners: {}},
9: {estimatedEats: 1, owners: {}}
}
},
6:{
petIds:{
113: {"estimatedEats": 5, "owners": {}},
9: {"estimatedEats": 6, "owners": {}},
1: {"estimatedEats": 7, "owners": {}}
}
}
};

var pets = [];
Object.keys(x).forEach(function(key) {
var y = x[key];
Object.keys(y).forEach(function(objKey) {
if(objKey === 'petIds'){
var z = y[objKey];
Object.keys(z).forEach(function(petKey) {
var pet = Object.assign({},z[petKey]);
pet.id = parseInt(petKey);
pets.push(pet);
});
};
});
});

var sumPets = [];

pets.forEach(function(p){
var idx = sumPets.findIndex(function(i){
return i.id === p.id;
});

if(idx < 0){
sumPets.push(p);
} else {
sumPets[idx].estimatedEats = sumPets[idx].estimatedEats + p.estimatedEats;
}
});

console.log(sumPets);

关于javascript - 在 Javascript 中解构对象字段并计算总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57385119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com