我试图从对象中获取基于id的classes数组。 (并存储)
const objs = {
"1":{
"name":"Candice",
"classes": [00029,00023,00032,000222],
"id":0002918
},
"2":{
"name":"Clark",
"classes":[000219,00029,00219],
"id":00032
}
}
const objsKeys = Object.keys(objs);
const userClasses = objKeys.find(a => objs[a].id === this.state.userId).classes
console.log(userClasses);
// expect output
[00029,00023,00032,000222]
// but returns
Uncaught TypeError: Cannot read property 'classes' of undefined
我在这里做错了什么?感谢您的帮助!
答案 0 :(得分:1)
您使用 Array#find
方法获取属性名称,并且您尝试获取字符串的classes
属性,undefined
。因此,您需要使用 Array#find
方法返回的属性名称从对象获取属性值。
const userClasses = objs[objKeys.find(a => objs[a].id === this.state.userId)].classes
答案 1 :(得分:0)
你只是得到钥匙。 尝试:
const objs = {
"1":{
"name":"Candice",
"classes": [00029,00023,00032,000222],
"id":0002918
},
"2":{
"name":"Clark",
"classes":[000219,00029,00219],
"id":00032
}
}
const objsKeys = Object.keys(objs);
//if you console.log the following, you get the property/key of 2:
console.log(objsKeys.find(a => objs[a].id === 00032))
// you need to use that property to get the object value
const userClasses = objs[objsKeys.find(a => objs[a].id === this.state.userId)].classes
console.log(userClasses);