Javascript复杂对象中项目的总和
我有一些数据,我正在计算,并将总数放入一个数组中 以下是数据和代码:Javascript复杂对象中项目的总和,javascript,Javascript,我有一些数据,我正在计算,并将总数放入一个数组中 以下是数据和代码: var data = { "cars": [ { "id": "1", "name": "name 1", "thsub": [ { "id": "11", "name": "sub 1",
var data = {
"cars": [
{
"id": "1",
"name": "name 1",
"thsub": [
{
"id": "11",
"name": "sub 1",
"stats": {
"items": 5,
},
"ions": null
},
{
"id": "22",
"name": "sub 2",
"stats": {
"items": 5,
},
"translations": null
}
],
"image": null
},
{
"id": "2",
"name": "name 2",
"thsub": [
{
"id": "33",
"name": "sub 43",
"stats": {
"items": 20,
},
"ions": null
},
{
"id": "44",
"name": "sub 76",
"stats": {
"items": 5,
},
"translations": null
}
],
"image": null
}
]
}
var thCount = [];
for(key in data.cars[0].thsub ){
if(data.cars[0].thsub[key].stats){
thCount.push(data.cars[0].thsub[key].stats.items);
}
}
console.log(thCount);
由于某种原因,“thCount”返回[5,5],而结果应该是:[10,25]
代码哪里出错了?您需要在汽车上再安装一个环路
var数据={
“汽车”:[{
“id”:“1”,
“名称”:“名称1”,
“thsub”:[{
“id”:“11”,
“名称”:“子1”,
“统计数据”:{
“项目”:5,
},
“离子”:空
}, {
“id”:“22”,
“名称”:“子2”,
“统计数据”:{
“项目”:5,
},
“翻译”:空
}],
“图像”:空
},
{
“id”:“2”,
“名称”:“名称2”,
“thsub”:[{
“id”:“33”,
“名称”:“第43分节”,
“统计数据”:{
“项目”:20,
},
“离子”:空
}, {
“id”:“44”,
“名称”:“sub 76”,
“统计数据”:{
“项目”:5,
},
“翻译”:空
}],
“图像”:空
}
]
}
var-thCount=[];
对于(var l=0,m=data.cars.length;l console.log(thCount)
您应该使用reduce()
和map()
方法。任何方法都可以使用回调函数
reduce()方法对累加器和每个累加器应用一个函数
数组的值(从左到右),以将其减少为单个
价值观
map()方法使用调用
在此数组中的每个元素上提供函数
var数据={
“汽车”:[
{
“id”:“1”,
“名称”:“名称1”,
“thsub”:[
{
“id”:“11”,
“名称”:“子1”,
“统计数据”:{
“项目”:5,
},
“离子”:空
},
{
“id”:“22”,
“名称”:“子2”,
“统计数据”:{
“项目”:5,
},
“翻译”:空
}
],
“图像”:空
},
{
“id”:“2”,
“名称”:“名称2”,
“thsub”:[
{
“id”:“33”,
“名称”:“第43分节”,
“统计数据”:{
“项目”:20,
},
“离子”:空
},
{
“id”:“44”,
“名称”:“sub 76”,
“统计数据”:{
“项目”:5,
},
“翻译”:空
}
],
“图像”:空
}
]
}
控制台.log(数据.cars.map)(功能(项){
return item.thsub.reduce(函数(a,b){return a.stats.items+b.stats.items;});
}));代码>针对您的问题的正确代码如下所示:
**var count = [];
for(var i = 0; i < data.cars.length; i++){
countSum = 0;
for(key in data.cars[i].thsub){
countSum = countSum + data.cars[i].thsub[key].stats.items;
}
count.push(countSum);
}**
**var count=[];
对于(变量i=0;i
尝试此代码,将解决您的问题。您的代码只查看数据。汽车[0]
。它不看数据。汽车[1]
。在@Pointy的版本中,您对[10,25]的期望是什么?通过计算items字段并将其添加到上面,您实际上并没有对任何内容进行求和(假设这是您的意图)。您的代码是否尝试执行任何数字相加操作?@PaulTenna2000,请查看我的方法,以便编写一个更简单的解决方案:)您应该解释一下这是如何工作的,而不仅仅是粘贴答案。谢谢你,伊万,当然。Ivan您刚刚丢失了data.cars数组的其他数组值。因此,我只是在第一个for循环中首先解析data.cars数组。然后将我能够从data.cars[index..n]中获取的每个stats.items的值添加到countSum变量,并将每个countSum推送到各自的count数组变量索引中。。
**var count = [];
for(var i = 0; i < data.cars.length; i++){
countSum = 0;
for(key in data.cars[i].thsub){
countSum = countSum + data.cars[i].thsub[key].stats.items;
}
count.push(countSum);
}**