gpt4 book ai didi

javascript - 获取 javascript 对象中特定键的总和

转载 作者:行者123 更新时间:2023-11-29 16:30:52 24 4
gpt4 key购买 nike

我想获取 js 对象中所有 menge 键的总和并将其存储在变量中。有人可以帮助我如何做到这一点吗?我的对象的片段:

var obj = {
"_15800175": {
"posID": "159469",
"scanID": "22597",
"anr": "15800175",
"TVanr": "",
"code": "G-09-27-2E",
"ean": "4710069680575",
"marke": "fox",
"bez": "jersey yellow",
"bez2": "size xl",
"menge": "1",
"ve": "St\u00fcck",
"Dimensionstext": "TT9857BG\r\n",
"Langtext": ""
},
"_15100027": {
"posID": "159471",
"scanID": "22597",
"anr": "15100027",
"TVanr": "",
"code": "G-11-03-2A",
"ean": "4712511825411",
"marke": "fox",
"bez2": "jersey L",
"menge": "1",
"ve": "St\u00fcck",
"Dimensionstext": "blue\r\n",
"Langtext": ""
}
}

最佳答案

您可以使用Object.values()Array.reduce(),如下所示:

var obj = {
"_15800175": {
"posID": "159469",
"scanID": "22597",
"anr": "15800175",
"TVanr": "",
"code": "G-09-27-2E",
"ean": "4710069680575",
"marke": "fox",
"bez": "jersey yellow",
"bez2": "size xl",
"menge": "1",
"ve": "St\u00fcck",
"Dimensionstext": "TT9857BG\r\n",
"Langtext": ""
},
"_15100027": {
"posID": "159471",
"scanID": "22597",
"anr": "15100027",
"TVanr": "",
"code": "G-11-03-2A",
"ean": "4712511825411",
"marke": "fox",
"bez2": "jersey L",
"menge": "1",
"ve": "St\u00fcck",
"Dimensionstext": "blue\r\n",
"Langtext": ""
},
"dummy": {
"menge": "not-convertable-to-integer"
},
"dummy2": {
// This item does NOT have "menge" property
}
}

var sumMenge = Object.values(obj).reduce((sum, item) => sum + (!isNaN(+item.menge) || 0),0);
// ^^^ This is to convert item.menge to number

console.log(sumMenge);

希望这有帮助

关于javascript - 获取 javascript 对象中特定键的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57906170/

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