JavaScript从嵌套对象中获取值

时间:2017-11-27 02:53:28

标签: javascript object for-loop nested nested-loops

如果这是我的对象:

{{1}}

我如何制作一个将每个价格打印到控制台的循环?

打印此值时,有没有办法追踪名称?

例如,如果输出为3.00,我如何创建一个能够给出3.00价格的名称的函数?

提前致谢!

3 个答案:

答案 0 :(得分:4)

回答你的问题:

function printPrice(obj) {
  if (obj.price)
    console.log(obj.name, obj.price)

  else for (key in obj)
    printPrice(obj[key])
}

var obj = {
  "bakery1": {
    "small": {
      "name": "Small cookie",
      "price": 0.75
    },
    "large": {
      "name": "Large cookie",
      "price": 3
    }
  },
  "bakery2": {
    "small": {
      "name": "Small cookie",
      "price": 1
    },
    "large": {
      "name": "Large cookie",
      "price": 4
    }
  }
};

printPrice(obj)

但是,对于这些类型的集合,使用数组可能更好。例如,我们可以这样做:

var bakeries = [
  {
    name: 'Bakery 1',
    menu: [
      {name: 'small cookie', price: 0.75},
      {name: 'large cookie', price: 3.00}
    ]
  },

  {
    name: 'Bakery 2',
    menu: [
      {name: 'small cookie', price: 1.00},
      {name: 'large cookie', price: 4.00}
    ]
  }
]

这使我们能够更好地组织每个项目的特定属性。在这种情况下,打印价格的代码变得更加简单:

bakeries
  .map(bakery => bakery.menu)
  .forEach(menu => menu.map(
    item => console.log(item.name, item.price)))

答案 1 :(得分:0)

运行它,看看它是如何工作的



var obj = {
  bakery1: {
    small: {
      name: "Small cookie",
      price: 0.75
    },
    large: {
      name: "Large cookie",
      price: 3.00
    }
  },
  bakery2: {
    small: {
      name: "Small cookie",
      price: 1.00
    },
    large: {
      name: "Large cookie",
      price: 4.00
    }
  }
};

Object.keys(obj).map((name) => {
  Object.keys(obj[name]).map((type) => document.write(`${name}-${type}-${obj[name][type].name}-${obj[name][type].price}<br/>`))
})
&#13;
&#13;
&#13;

答案 2 :(得分:0)

递归函数。

function objSearch(serObj){
    // For loop through the object.
    for( prop in serObj ){
        // If the property is price get the price.
        if(prop === 'price'){
            // Got the price property now return the value of price.
            console.log('I have price...', prop, '=', serObj[prop]);
            // If the property is an object send it through the function again.
        } else if(typeof serObj[prop] === 'object'){  
            // Pass the nested object.
            objSearch(serObj[prop]);
        }
    }
}

objSearch(obj);