簡體   English   中英

如何將帶有對象的數組推入數組

[英]How to push an array with objects into an array

我是這里的新手,所以我的問題可能聽起來很愚蠢。

我有一個包含多個對象的數組,我不確定如何將每個 object 的鍵名推送到數組中。

這是我的代碼:

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 = [];

我試過了:

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

但它返回整個數組,即使我在這里的 select 成分[I] 我要選擇的元素仍然無法正常工作。 如果有人有想法,我將不勝感激。 非常感謝。

使用 es6,您可以使用map

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

你非常親近。 這將推送ingredients數組中每個 object 的name

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

您可以使用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);

只是不要忘記花生后面的逗號!

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