我想获取我的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": ""
}
}
答案 0 :(得分:4)
您可以像下面这样使用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);
希望这会有所帮助
答案 1 :(得分:1)
您可以做的是迭代主对象的键,然后将其减少为总和,即:
Object.keys(obj).reduce((acc, key) => acc = obj[key].menge + acc, 0)
答案 2 :(得分:0)
获取键数组后使用string general = doc.SelectSingleNode("/files/file[not(@product)]").InnerText;
.reduce()
答案 3 :(得分:0)
您需要将对象键放入数组中。
var id=Object.keys(obj); //get all keys
var menge=0;// init...
for (i=0;i<id.length;i++){// run over all keys found
menge=menge+obj[id[i]].menge; /add the things
}
console.log(menge);//see result
请参阅Object.keys
答案 4 :(得分:0)
您可以使用for (prop in obj)
遍历对象的属性名称。然后,您可以简单地使用total += +obj[prop].menge || 0;
。在这里+obj[prop].menge
将转换为number
。 +obj[prop].menge || 0;
如果对象不包含0
属性,则此行将返回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": ""
}
}
let total = 0;
for (prop in obj) {
total += +obj[prop].menge || 0;
}
console.log(total);