简体   繁体   中英

How to push an array with objects into an array

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.

with es6 you can use map

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

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);
}

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

Just don't forget the comma after peanut!

var myIngredients = [];

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

console.log(myIngredients)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM