繁体   English   中英

如何访问另一个对象内的对象属性

[英]how to access object properties inside another object

我有一个看起来像这样的结构:

Customer {
  name: 'jen',
  options:
   [ Order {
       _price: 11,
       _option: 'vegan',
       _name: 'V for Vegan',
       _ingredients:
        [ Ingredient { name: 'mint', price: 0.5 },
          Ingredient { name: 'peanuts', price: 0.5 } ] },
     Order {
       _price: 11,
       _option: 'vegetarian',
       _name: 'Veggie',
       _ingredients: [] } ] }

我很难退出这个部分:

_ingredients:
            [ Ingredient { name: 'mint', price: 0.5 },
              Ingredient { name: 'peanuts', price: 0.5 } ] },

我可以注销这个:

Options: vegan
[object Object],[object Object]

Options: vegetarian

但我希望它是这样的

Options: vegan
mint, peanuts

我的最后一次尝试是循环_ingredients但它返回undefined。 我的代码到目前为止:

getBill() {
      let totalPrice = 0;

      console.log(`
        Your current bill:
        `)

      this.options.forEach((i) => {
        console.log(`
          Option: ${i._option}
          Extra Ingredients: ${i._ingredients.forEach((j) => {j.name})}
        `)
        totalPrice += i._price;
      })

      console.log(`
        Total Price: ${totalPrice} $
        `)
    }

这是一个JavaScript函数错误,因为forEach实际上并没有返回任何有用的东西。 如果你阅读文档,你会看到返回值被明确指定为undefined ,这是你可能得到的。 你需要做些什么,比如加入它们。

Extra Ingredients: ${i._ingredients.map(_i => _i.name).join(', ')}

使用Lodash下划线会给你一个map功能需要一个字符串,以及:

Extra Ingredients: ${_.map(i._ingredients, 'name').join(', ')}

这实际上返回了你想要的值,它会取出name属性,然后你可以使用join进行美化处理,将它组合成一个格式良好的字符串列表。

暂无
暂无

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

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