我有以下物品,我想总结相同成分名称的值,如:番茄:5,鸡肉:5,米饭:1,豌豆:1,我有这个代码,但没有总和,而是显示所有对象
var data3 = {
"menus": [{
"recipe": "chicken with rice",
"ingredients": [{
"name": "tomato",
"value": 2
}, {
"name": "chicken",
"value": 3
}, {
"name": "rice",
"value": 1
}]
}, {
"recipe": "Garden rice",
"ingredients": [{
"name": "tomato",
"value": 3
}, {
"name": "chicken",
"value": 2
}, {
"name": "peas",
"value": 1
}]
}]
};
var ingredients;
for (var i = 0; i < 10; i++) {
ingredients = data3.menus[i].ingredients;
var temp = {};
var obj = null;
for (var j = 0; j < ingredients.length; j++) {
obj = ingredients[j];
if (!temp[obj.name]) {
temp[obj.name] = obj;
} else {
temp[obj.name].value += obj.value;
}
}
var result = [];
for (var prop in temp)
result.push(temp[prop]);
console.log(result);
};
感谢您的帮助,谢谢!
答案 0 :(得分:4)
如果属性不存在,您可以使用带有成分名称的哈希表,并使用默认值零。然后添加值。
var data3 = { menus: [{ recipe: "chicken with rice", ingredients: [{ name: "tomato", value: 2 }, { name: "chicken", value: 3 }, { name: "rice", value: 1 }] }, { recipe: "Garden rice", ingredients: [{ name: "tomato", value: 3 }, { name: "chicken", value: 2 }, { name: "peas", value: 1 }] }] },
ingredients = Object.create(null);
data3.menus.forEach(function (a) {
a.ingredients.forEach(function (b) {
ingredients[b.name] = (ingredients[b.name] || 0) + b.value;
});
});
console.log(ingredients);
&#13;
答案 1 :(得分:0)
你的实现是正确的,只是你一次又一次地重新初始化temp。所以你只需要从你的for循环中取出temp。
var data3 = {
"menus": [{
"recipe": "chicken with rice",
"ingredients": [{
"name": "tomato",
"value": 2
}, {
"name": "chicken",
"value": 3
}, {
"name": "rice",
"value": 1
}]
}, {
"recipe": "Garden rice",
"ingredients": [{
"name": "tomato",
"value": 3
}, {
"name": "chicken",
"value": 2
}, {
"name": "peas",
"value": 1
}]
}]
};
var ingredients;
var temp = {};
for (var i = 0; i < data3.menus.length; i++) {
ingredients = data3.menus[i].ingredients;
var obj = null;
for (var j = 0; j < ingredients.length; j++) {
obj = ingredients[j];
if (!temp[obj.name]) {
temp[obj.name] = obj;
} else {
temp[obj.name].value += obj.value;
}
}
};
var result = [];
for (var prop in temp)
result.push(temp[prop]);
console.log(result);
答案 2 :(得分:0)
您可以创建一个将遍历所有成分的函数,如果ingredient.name
已给出名称,则将ingredient.value
添加到结果中。这是带有箭头功能的ES2015解决方案:
const sumIngredients = (menus, name) => {
let result = 0;
menus.forEach(meal => {
meal.ingredients.forEach(ingredient => {
if (ingredient.name === name) {
result += ingredient.value;
}
})
})
return result;
}
使用它:
sumIngredients(data3.menus, 'chicken'); //5
sumIngredients(data3.menus, 'tomato'); //5
sumIngredients(data3.menus, 'rice'); //1
sumIngredients(data3.menus, 'peas'); //1