如何遍历嵌套对象-JavaScript

时间:2019-11-22 00:59:19

标签: javascript

所以我有一个带有嵌套对象的数组,我想用forEach()方法来遍历它。最后,我希望有4个看起来像这样的句子:

  • 果冻甜甜圈每个$ 1.22
  • 巧克力甜甜圈每个售价$ 2.45
  • 苹果甜甜圈每个1.59美元
  • 波士顿奶油甜甜圈每个售价$ 5.99

我以为我需要一个内部循环来解决各个项目,但是我不确定。非常感谢您的帮助。到目前为止,这是我的代码:

var donuts = [
  { type: "Jelly", cost: 1.22 },
  { type: "Chocolate", cost: 2.45 },
  { type: "Cider", cost: 1.59 },
  { type: "Boston Cream", cost: 5.99 }
];

donuts.forEach(function(elem) {
  for (i=0; i<elem.length; i++) {
    let type = donuts[i].type
    let cost = donuts[i].cost
    console.log(type + " donuts cost $" + cost + " each");  
  }
});

1 个答案:

答案 0 :(得分:1)

forEach()为数组中的每个元素调用一次提供的回调函数。甜甜圈是代表各个甜甜圈的javascript对象数组。

var donuts = [{
        type: "Jelly",
        cost: 1.22
    },
    {
        type: "Chocolate",
        cost: 2.45
    },
    {
        type: "Cider",
        cost: 1.59
    },
    {
        type: "Boston Cream",
        cost: 5.99
    }
];

donuts.forEach(function(donut) {

    console.log(donut.type + " donuts cost $" + donut.cost + " each");
});