从多维对象中获取数组
Get array from a multidimensional object
我试图从对象中获取基于 id 的 类 数组。 (并存储)
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
我在这里做错了什么?提前感谢您的帮助!
您正在使用 Array#find
method, and you are trying to get classes
property of string and which is undefined
. So you need to get the property value from object using the property name returned by Array#find
方法获取 属性 名称。
const userClasses = objs[objKeys.find(a => objs[a].id === this.state.userId)].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);
//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);
我试图从对象中获取基于 id 的 类 数组。 (并存储)
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
我在这里做错了什么?提前感谢您的帮助!
您正在使用 Array#find
method, and you are trying to get classes
property of string and which is undefined
. So you need to get the property value from object using the property name returned by Array#find
方法获取 属性 名称。
const userClasses = objs[objKeys.find(a => objs[a].id === this.state.userId)].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);
//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);