2017-07-15 43 views
0

我想從一個數組對象訪問數據:之後使用變量。 (代替屬性名稱)。 JavaScript的

{ 
    "results": [{ 
     "ID": "aaa", 
     "12/06/2017": "1", 
     "13/06/2017": "0", 
     "14/06/2017": "1", 
     "15/06/2017": "1", 
     "16/06/2017": "0", 
     "17/06/2017": "1", 
     "18/06/2017": "0" 
    } 
    ] 
} 

我通常這樣做的:

$.each(data.results, function (index, item) { 
        var eachrow = "<tr>" 
        + "<td>" + item.ID + "</td>" 
        ect... 
    $('#tbody').append(eachrow); 
         } 

但在這種情況下,屬性名稱將與每個搜索改變,因此我不能只寫他們。我知道什麼值將搜索之前,所以我可以將它們分配給變量,但item.variable不起作用。 我試過了:item。[variable]和item.arr [1]但我無法獲取任何東西。

感謝您的幫助

+0

如果你不知道密鑰,你可以通過'object.keys' – adeneo

+0

來獲取它們。輸出:功能鍵(){ [native code] } ??? – james

+0

我是個笨蛋,不過console.log(Object.keys(data.results));輸出仍然無用的[「0」] – james

回答

0

假設這是您的result

const result = { 
    "results":[ 
    { 
     "ID":"aaa", 
     "12/06/2017":"1", 
     "13/06/2017":"0", 
     "14/06/2017":"1", 
     "15/06/2017":"1", 
     "16/06/2017":"0", 
     "17/06/2017":"1", 
     "18/06/2017":"0" 
    } 
    ] 
}; 

那麼你可以做些什麼來讓所有的鍵值對是

const firstResult = result.results[0]; 
Object.keys(firstResult) 
    .map(key => { 
    const value = firstResult[key]; 
    return { key, value }; 
    }) 
    .forEach(process); 

而且process功能像這樣:

const process = ({ key, value }) => { 
    console.log(`The value of ${key} is ${value}`); 
};