我試圖通過匯總物件下每個鍵值對的總數來合并物件陣列。例如,下面的陣列將產生一個物件,其中包含totals3 個蘋果和 5 個橙子的物件。這應該是動態的。如果 pears 是另一個物件中的鍵,則生成的物件將在該totals物件下包含三個鍵:apples、oranges 和 pears。
樣本輸入:
[
{
summary: {
totals: {
apples: 2,
oranges: 3
}
}
},
{
summary: {
totals: {
apples: 1,
oranges: 2
}
}
}
]
預期輸出:
{
summary:{
totals:{
apples:3,
oranges:5
}
}
}
我試過的:
function mergeObjects(arr) {
let shape = {
summary:{
totals:{}
}
}
return arr.reduce((prev, cur) => {
if(cur.summary.totals.apples){
shape.summary.totals.apples.push(cur.summary.totals.apples)
}
}, shape);
}
uj5u.com熱心網友回復:
- 使用
Array#reduce, 在更新物件時迭代陣列 - 在每次迭代中,使用
Object#entriesand 迭代當前總計對并更新累加器。
const arr = [
{ summary: { totals: { apples: 2, oranges: 3 } } },
{ summary: { totals: { apples: 1, oranges: 2 } } },
];
const res = arr.reduce((map, current) => {
const { totals: currentTotals = {} } = current.summary ?? {};
const { totals } = map.summary;
Object.entries(currentTotals).forEach(([ key, value ]) => {
totals[key] = (totals[key] ?? 0) value;
});
return map;
}, { summary: { totals: {} } });
console.log(res);
uj5u.com熱心網友回復:
你可以試試類似的東西。只需遍歷陣列并總結蘋果和橙子。
const arr = [
{
summary: {
totals: {
apples: 2,
oranges: 3,
},
},
},
{
summary: {
totals: {
apples: 1,
oranges: 2,
},
},
},
];
function mergeObjects(arr) {
let shape = {
summary:{
totals:{
apples:0,
oranges:0
}
}
}
arr.forEach(x => {
if(x.summary.totals.apples){
shape.summary.totals.apples = x.summary.totals.apples;
shape.summary.totals.oranges = x.summary.totals.oranges;
}
});
return shape;
}
let result = mergeObjects(arr);
console.log(result);
uj5u.com熱心網友回復:
reduce 函式的第二個選項初始化值。
并且初始化的值可以在prev中使用!
[1] 將值存盤在 prev 中。
[2] prev 可以累加值。您必須回傳才能使用累積值。如果未回傳,則該值將是未定義的。
[3] apples 不是陣列型別,所以不能使用 push 方法。它是數字型別,您必須使用數字運算子。
function mergeObjects(arr) {
const shape = {
summary: {
totals: {},
},
};
return arr.reduce((prev, cur) => {
const { apples, oranges } = cur.summary.totals;
// [1]
prev.summary.totals.apples
// [3]
? (prev.summary.totals.apples = apples)
: (prev.summary.totals.apples = apples);
prev.summary.totals.oranges
? (prev.summary.totals.oranges = oranges)
: (prev.summary.totals.oranges = oranges);
// [2]
return prev;
}, shape);
}
尖端!
- 使用解構賦值
const { apples, oranges } = cur.summary.totals;
- 使用三元運算子
prev.summary.totals.apples
? (prev.summary.totals.apples = apples)
: (prev.summary.totals.apples = apples);
- 讓代碼看起來不錯!
uj5u.com熱心網友回復:
您可以將Object.entries()與Array#reduce()和Array.forEach()結合使用
代碼:
const data = [{summary: {totals: {apples: 2,oranges: 3}}},{summary: {totals: {apples: 1,oranges: 2}}}]
const result = data.reduce((a, c) => {
Object
.entries(c.summary.totals)
.forEach(([k, v]) => a.summary.totals[k] = v)
return a
},
{ summary: { totals: { apples: 0, oranges: 0 } } })
console.log(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476202.html
標籤:javascript 数组
