根据一系列配料(格式设置为对象)创建购物清单

时间:2018-07-08 00:38:24

标签: javascript arrays for-loop javascript-objects

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数组进行比较(添加对象之后)似乎是一个问题。

3 个答案:

答案 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);