如果你有一個這樣的物件陣列:

在每個物件中添加所有數值的最佳方法是什么,所以每個物件看起來像這樣:
{category: "A", total: 44}
所以在原始陣列的第 0 項中,0 23 21 是 24,現在由新的 'total' 鍵表示。
請記住,原始陣列中具有數值的“鍵”(例如“col2”)是隨機生成的(因此,像原始陣列這樣的另一個陣列可以具有“somethingelse”之類的鍵。
我已經嘗試過以下方法,但我認為它寫得不正確:
newArrayOfObjects.forEach(element => {
Object.values(element).reduce((a, b) => a b);
});
知道可能很好,但“關鍵”類別始終存在于每個物件中并且是固定的。所有其他鍵值都是數字的,并且總是不止一個。
uj5u.com熱心網友回復:
請檢查這個。
const array = [
{
category: 'A',
col1: 1,
col2: 2,
col3: 3,
},
{
category: 'B',
col1: 2,
col2: 3,
col3: 4,
}
]
const result = array.map(obj => {
const total = Object.values(obj).reduce((acc, value) => {
if (typeof value === 'number') {
return acc value;
}
return acc;
}, 0)
return {
category: obj.category,
total
}
})
console.log(result)
uj5u.com熱心網友回復:
O(n) 復雜度:
let result = [];
newArrayOfObjects.forEach((object) => {
let newItem = { category: object.category, total: object.col2 object.col3 };
result.push(newItem);
});
uj5u.com熱心網友回復:
您可以使用Array.map()withArray.reduce()來對陣列中的數值求和。
我們將創建一個toNumber()函式來獲取任何屬性的數值。如果這不是數字,它將回傳 0(保持總數不變)。
let arr = [
{ a: 0, category: "a", col2: 23, col3: 21 },
{ b: 0, category: "b", x: 100, y: 10, z: 1 },
{ j: 0, category: "x", foo: 25, bar: 50, meta: 'content' },
]
function toNumber(n) {
return isNaN(n) ? 0: n;
}
function sumTotals(a) {
return a.map(({ category, ...obj}) => {
const total = Object.values(obj).reduce((total, value) => {
return total toNumber(value);
}, 0);
return { category, total };
})
}
console.log('Totals:', sumTotals(arr))
.as-console-wrapper { max-height: 100% !important; }
uj5u.com熱心網友回復:
arr = [{x:1}, {x:3}]
arr.reduce((accumulator, current) => accumulator current.x, 0);
uj5u.com熱心網友回復:
var data = [
{ "category": "A", "col0": 5, "col1": 8, "some": "thing"},
{ "category": "B", "col1": 3, "col2": 5}
];
var res = data.map((it) => {
const { category, ...rest } = it;
return { ...it, total: Object.values(rest).reduce((prev, curr) => typeof curr === "number" ? prev curr : prev, 0)}
});
console.log(res);
/**
[
{"category":"A","col0":5,"col1":8,"some":"tst","total":13},
{"category":"B","col1":3,"col2":5,"total":8}
]
**/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/493256.html
標籤:javascript 数组 json 目的
