var ingredients = [
{ name: 'potatoes', quantity: 4 },
{ name: 'butter', quantity: 1 },
{ name: 'milk', quantity: 1, description: '1 cup' },
{ name: 'potatoes', quantity: 3 },
{ name: 'oil', quantity: 1, description: '3 cups' } ];
const shoppingList = [];
for (let i = 0; i < ingredients.length; i ++) {
for (let j = 0; j < shoppingList.length; j ++){
let ingredient = ingredients[i];
let shoppingListItem = shoppingList[j];
if(ingredient === shoppingListItem){
break;
}else if (roughDraftItem.name === shoppingListItem.name){
shoppingListItem.quantity += roughDraftItem.quantity;
} else {shoppingList.push(roughDraftItem);
}
}
}
当我运行此代码时,shoppingList数组返回为空。当我执行第二个循环时,代码没有问题,我得到了我需要的
shoppingListItem = { name: 'potatoes', quantity: 1}
尝试将Ingredients数组与shoppingList数组进行比较(添加对象之后)似乎是一个问题。
答案 0 :(得分:0)
您的shoppingList
为空,因此其length = 0
。数组的第二个循环未运行,因为它被告知运行0
次。
您不需要第二个循环即可将对象添加到shoppingList
,因此我将其删除。
答案 1 :(得分:0)
正如其他人所说,shoppingList
的长度为0,因此第二个循环将永远不会运行。另外,如果您要对具有相同名称的项目数量求和,则可以使用reduce
来简化:
const ingredients = [
{ name: 'potatoes', quantity: 4 },
{ name: 'butter', quantity: 1 },
{ name: 'milk', quantity: 1, description: '1 cup' },
{ name: 'potatoes', quantity: 3 },
{ name: 'oil', quantity: 1, description: '3 cups' } ];
const result = ingredients.reduce((acc, curr) => {
const exists = acc.find(item => item.name === curr.name);
if (exists) {
exists.quantity += curr.quantity;
return acc;
}
return [...acc, curr]
}, []);
console.log(result);
答案 2 :(得分:0)
您可以使用Array.prototype.reduce
和ES6对象解构分配按名称进行成分汇总,并使用Array.prototype.map
生成所需的输出:
此解决方案比嵌套for
循环更具声明性,并且可以处理任意数量的重复项:
var ingredients = [
{ name: 'potatoes', quantity: 4 },
{ name: 'butter', quantity: 1 },
{ name: 'milk', quantity: 1, description: '1 cup' },
{ name: 'potatoes', quantity: 3 },
{ name: 'oil', quantity: 1, description: '3 cups' }
];
// Aggregate `quantity` by `name`
var dataObj = ingredients.reduce((all, {name, quantity}) => {
all[name] = (all[name] || 0) + quantity;
return all;
}, {});
// Generate the result
var shoppingList = Object.keys(dataObj).map(ing => ({name: ing, quantity: dataObj[ing]}));
console.log(shoppingList);