0

I am a newbie here so my question may sound stupid.

I have an array with multiple objects and I am not sure how to push the key name of each object to an array.

This is my code:

var ingredients = [
    { id: 1, name: "onion", mineralsUnit: "mg", water: 89.11 },
    { id: 2, name: "carrot", calcium: 23, iron: 0.21, otherUnit: "g", water: 89.11 },
    { id: 3, name: "peanut", iron: 0.21, otherUnit: "g", water: 89.11 }
];

and I've created a new empty array where I want to add just the name from the first array

var myIngredients = [];

I've tried that:

for (var i = 0; i < ingredients.length; i++) {
    myIngredients.push(ingredients[i]);
}

but it returns the entire array and even though I select in here ingredients[I] what element I want to pick it's still not working. If someone has an idea I would really appreciate it. Thanks a lot.

1
  • you're just pushing all of the ingredients elements into myIngredients by cycling on ingredients. i will be the index of the ingredients array, so you're actually not choosing anything Commented Apr 29, 2020 at 15:19

4 Answers 4

4

with es6 you can use map

try myIngredients = ingredients.map(ingredient => ingredients.name)

Sign up to request clarification or add additional context in comments.

1 Comment

Even the foreach way has been chosen, I still recommend to use map which is more clean. this answer may help (stackoverflow.com/a/49549799/12704953 ) @Alexandra
2

You were very close. This will push the name value of every object in the ingredients array

  for (var i = 0; i < ingredients.length; i++) {
  myIngredients.push(ingredients[i].name);
}

Comments

1

Just don't forget the comma after peanut!

var myIngredients = [];

ingredients.forEach(
  ingredient =>
  myIngredients.push(ingredient.name)
)

console.log(myIngredients)

2 Comments

if you use arrow function, map is better than foreach
btw map under the hood does a for loop.
1

You can use the map function:

var ingredients = [
  { id: 1, name: "onion", mineralsUnit: "mg", water: 89.11},
  { id: 2, name: "carrot", calcium: 23, iron: 0.21, otherUnit: "g", water: 89.11 },
  { id: 3, name: "peanut", iron: 0.21, otherUnit: "g", water: 89.11, }
];

var myIngredients = ingredients.map(e => e.name);

console.log(myIngredients);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.