简体   繁体   English

如何将带有对象的数组推入数组

[英]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.我有一个包含多个对象的数组,我不确定如何将每个 object 的键名推送到数组中。

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.但它返回整个数组,即使我在这里的 select 成分[I] 我要选择的元素仍然无法正常工作。 If someone has an idea I would really appreciate it.如果有人有想法,我将不胜感激。 Thanks a lot.非常感谢。

with es6 you can use map使用 es6,您可以使用map

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

You were very close.你非常亲近。 This will push the name value of every object in the ingredients array这将推送ingredients数组中每个 object 的name

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

You can use the map function:您可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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