[英]how to access object properties inside another object
I have a structure that looks like this: 我有一个看起来像这样的结构:
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: [] } ] }
I'm having a hard time logging out this part: 我很难退出这个部分:
_ingredients:
[ Ingredient { name: 'mint', price: 0.5 },
Ingredient { name: 'peanuts', price: 0.5 } ] },
I can get to log out this: 我可以注销这个:
Options: vegan
[object Object],[object Object]
Options: vegetarian
But I would like it to be something like 但我希望它是这样的
Options: vegan
mint, peanuts
My last attempt was looping through _ingredients but it is returning undefined. 我的最后一次尝试是循环_ingredients但它返回undefined。 My code so far:
我的代码到目前为止:
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} $
`)
}
It's a JavaScript function error as forEach
doesn't actually return anything useful. 这是一个JavaScript函数错误,因为
forEach
实际上并没有返回任何有用的东西。 If you read the documentation you'll see the return value is explicitly specified as undefined
, which is what you're probably getting. 如果你阅读文档,你会看到返回值被明确指定为
undefined
,这是你可能得到的。 You'll need to do something with that, like join them together. 你需要做些什么,比如加入它们。
Extra Ingredients: ${i._ingredients.map(_i => _i.name).join(', ')}
Using Lodash or Underscore will give you a map
function that takes a string as well: 使用Lodash或下划线会给你一个
map
功能需要一个字符串,以及:
Extra Ingredients: ${_.map(i._ingredients, 'name').join(', ')}
That actually returns the values you want, it plucks out the name
property, which you can then give a cosmetic treatment with the join
to combine it into a well-formed string list. 这实际上返回了你想要的值,它会取出
name
属性,然后你可以使用join
进行美化处理,将它组合成一个格式良好的字符串列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.