2016-06-30 180 views
0

我試圖從對象中獲取基於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 

我在做什麼錯在這裏?提前謝謝你的幫助!

+0

'this.state.userId'的值是什麼? – Timo

+0

@TimoSta 1或2。對象鍵(不是id值)。它應該檢查它們是否匹配(對象鍵和狀態ID) – Modelesq

+0

可能是一個整數? '==='比較值和類型,所以'1 ==='1''等於'false'。 – Timo

回答

1

你得到使用Array#find方法屬性名,而你試圖讓字符串classes財產,哪些是undefined。因此,您需要使用由Array#find方法返回的屬性名稱從對象獲取屬性值。

const userClasses = objs[objKeys.find(a => objs[a].id === this.state.userId)].classes 
0

你只得到鑰匙。 Try:

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