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.

Mickael B.
  • 4,755
  • 4
  • 24
  • 48
  • 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 – CapitanFindus Apr 29 '20 at 15:19

4 Answers4

4

with es6 you can use map

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

devosu
  • 99
  • 6
  • 2
    Even the foreach way has been chosen, I still recommend to use map which is more clean. this answer may help (https://stackoverflow.com/a/49549799/12704953 ) @Alexandra – devosu Apr 29 '20 at 16:28
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);
}
Ivan V.
  • 7,593
  • 2
  • 36
  • 53
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);
Mickael B.
  • 4,755
  • 4
  • 24
  • 48
1

Just don't forget the comma after peanut!

var myIngredients = [];

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

console.log(myIngredients)
Alan Deep
  • 2,037
  • 1
  • 14
  • 22