JavaScript 从嵌套对象中获取值 [英] JavaScript get value from nested object

查看:46
本文介绍了JavaScript 从嵌套对象中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这是我的对象:

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

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

How would I go about making a loop that prints every price to the console?

当这个值被打印出来时,有没有办法追踪这个名字?

And when this value is printed, is there a way to trace the name?

例如,如果输出为 3.00,我将如何创建一个函数,该函数为我提供与 3.00 价格相匹配的名称?

For example if the output is 3.00 how would I make a function that gives me the name that goes with the 3.00 price?

提前致谢!

推荐答案

回答您的问题:

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)

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

However, for these kinds of collections, it might be better to use an array. For example, we could do something like this:

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}
    ]
  }
]

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

This enables us to better organize the specific properties of each item. In this case, the code to print the prices becomes much simpler:

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

这篇关于JavaScript 从嵌套对象中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆