![](/img/trans.png)
[英]JavaScript destructuring object containing fields with special characters
[英]Destructuring an Object fields and Calculating the Sum in Javascript
我在弄清楚如何分解和添加帶有字段的對象的總和時遇到麻煩。 以前,我們破壞對象數組中的單獨對象。 現在,它們被歸納為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);
我不太確定我了解您要達到的目標,但是我會盡力回答:)
有沒有一種方法可以將每個字段轉換為對象數組? 我認為這樣做和映射數組會更容易。
Object.values
創建一個包含對象所有值的數組。 那是您要找的東西嗎?
這里有一個codepen這里我總結estimatedEats
使用Object
和Array
的方法。 我認為您也可以基於此總結其他屬性。
const data = {
3: {
petIds: {
113: {
estimatedEats: 10,
owners: { female: { kids: 1, adult: 2, senior: 10 } },
male: { kids: 1, adult: 2, senior: 10 }
},
1: {
estimatedEats: 120,
owners: { female: { kids: 1, adult: 2, senior: 10 } },
male: { kids: 1, adult: 2, senior: 10 }
}
}
},
6: {
petIds: {
113: {
estimatedEats: 5,
owners: { female: { kids: 1, adult: 2, senior: 10 } },
male: { kids: 1, adult: 2, senior: 10 }
},
1: {
estimatedEats: 5,
owners: { female: { kids: 1, adult: 2, senior: 10 } },
male: { kids: 1, adult: 2, senior: 10 }
}
}
}
};
const groupedById = Object.values(data).reduce((acc, { petIds }) => {
Object.entries(petIds).forEach(([key, value]) => {
acc[key] = acc[key] || [];
acc[key].push(value);
});
return acc;
}, {});
const summedUp = Object.entries(groupedById).map(
([key, value]) =>
value.reduce(
(acc, row) => {
acc.estimatedEats += row.estimatedEats;
return acc;
},
{ estimatedEats: 0, petIds: key }
),
[]
);
console.log("Result:", summedUp);
更新:也將代碼粘貼到我的答案中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.