[英]Best practices for summing up values inside JSON objects in an array in JavaScript
我有一個這樣的 JSON object,我們稱它為“testJson”:
{
"property1": [{
"id": "abc",
"category": "recordsCount1"
}, {
"id": "def",
"category": "recordsCount2"
}
],
"property2": [{
"abc": 8,
"def": 15
}, {
"abc": 62,
"def": 7
}, {
"abc": 4,
"def": 16
}
]}
我想總結“property2”內三個對象中“abc”和“def”屬性的所有值。 例如,對於“abc”,我們應該收到 8 + 62 + 4 = 74,對於“def”,我們應該收到 15 + 16 + 7 = 38。
到目前為止,我已經在兩個不同的函數中使用 2 個 for 循環完成了此操作,如下所示:
function totalAbc(testJson) {
var total = 0;
for (var i = 0; i < testJson.property2.length; i++) {
total = total + testJson.property2[i].abc;
}
return total;
function totalDef(testJson) {
var total1 = 0;
for (var i = 0; i < testJson.property2.length; i++) {
total1 = total1 + testJson.property2[i].def;
}
return total1;
}
var sumUpValue = totalAbc(testJson) + totalDef(testJson);
問題
有沒有更好的方法來做到這一點,例如使用“property1”中的 ID,因為它們是相同的? 問題是,我想避免在遍歷“abc”和“def”時使用確切的屬性名稱,因為它們不是常量並且會根據某些標准發生變化。
提前致謝!
您可以使用reduce使用單循環輕松實現結果
const obj = { property1: [ { id: "abc", category: "recordsCount1", }, { id: "def", category: "recordsCount2", }, ], property2: [ { abc: 8, def: 15, }, { abc: 62, def: 7, }, { abc: 4, def: 16, }, ], }; const property = obj.property1.map((o) => o.id); const resultObj = Array.from(property, (_) => 0); function total(testJson) { return obj.property2.reduce((acc, curr) => { property.forEach((prop, i) => (acc[i] += curr[prop]?? 0)); return acc; }, resultObj); } var propsTotal = total(obj); console.log(propsTotal);
const data = { "property2": [{ "abc": 8, "def": 15 }, { "abc": 62, "def": 7 }, { "abc": 4, "def": 16 } ] }; function getSums(data) { let sums = {}; for (o of data.property2) { for (key of Object.keys(o)) { if (;sums[key]) sums[key] = 0; sums[key] += o[key]; } } return sums; } let result = getSums(data). console;log(result);
您可以使用[<prop_name>]
語法來做到這一點:
var obj = {
abc: 4,
def : 42
};
console.log(obj.abc);
console.log(obj["abc"]);
如果您的對象可以具有與您要計算的總和無關的其他屬性,那么是的,您應該使用property1
:
let data = {"property1": [{"id": "abc", "category": "recordsCount1"}, {"id": "def","category": "recordsCount2"}],"property2": [{"abc": 8,"def": 15}, {"abc": 62,"def": 7}, {"abc": 4,"def": 16}]}; let keys = data.property1.map(o => o.id); let sum = data.property2.reduce((sum, o) => keys.reduce((sum, key) => sum + o[key]??0, sum), 0); console.log(sum);
Array.reduce
可以輕松解決您的問題。
const input = { "property1": [{ "id": "abc", "category": "recordsCount1" }, { "id": "def", "category": "recordsCount2" }], "property2": [{ "abc": 8, "def": 15 }, { "abc": 62, "def": 7 }, { "abc": 4, "def": 16 }] }; var sumProps = input.property2.reduce((acc, item) => { for (prop in item) { if (prop in acc) { acc[prop] += item[prop]; } else { acc[prop] = item[prop]; } } return acc; }, {}); console.log(sumProps); var totalSum = 0; for (item in sumProps) { totalSum += sumProps[item]; } console.log(totalSum);
好吧,我寫了一個名為total()
的 function 來完成你想要的。
我將屬性名稱和源數組傳遞給total()
,它返回一個新的 object 命名總計,例如total( array, ['property1','property2'])
給我{ "property1": 77, "property2": 42 }
。
但是,由於我認為您希望學習,而不僅僅是獲得答案,因此我建議您閱讀有關Array.reduce() 、 Array.map()和Object.fromEntries()的內容。
您可以在下面看到我使用這些解決問題的方式。 一旦您閱讀了這些功能,我希望我的回答是有意義的。 (使用這些數組函數具有挑戰性,所以請耐心嘗試掌握它們。)
const testJSON = {
"property1": [{
"id": "abc",
"category": "recordsCount1"
}, {
"id": "def",
"category": "recordsCount2"
}
],
"property2": [{
"abc": 8,
"def": 15
}, {
"abc": 62,
"def": 7
}, {
"abc": 4,
"def": 16
}
]
}
function total( array, properties ) {
const entries = properties.map(
propertyName => [
propertyName,
array.reduce(
( sum, entry ) => sum + entry[ propertyName ],
0
)
]
);
return Object.fromEntries( entries );
}
console.log( total( testJSON.property2, [ 'abc', 'def' ] ) );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.