2016-02-25 47 views
0

我想獲取嵌套對象的值而不使用它的鍵。像例如,如果我有一個像如何以通用方式遍歷嵌套對象

var a = {"key" : "100"}

一個對象,我不希望使用a.key,得到的結果,雖然我有嵌套的對象,它已成爲我很難獲取的價值,這是我曾嘗試過:

var Obj = [{"ghi":{"content":"abc"}},{"def":{"imgURL":"test.png"}},{"abc":{"key":"001"}},{"ghi":{"content":"abc"}},{"def":{"imgURL":"test.png"}},{"abc":{"key":"001"}}] 

for(var key in Obj){ 
abc = Obj[key] 
for(var j in abc){ 
    def = abc[key] 
} 
} 

所以我需要所有對象的值,而不直接使用密鑰。

+0

和值像你得到什麼? –

+0

@Nina Scholz,在ghi下,有我需要的內容值和類似於我的數組 –

+0

中的所有對象,但是您有多個'ghi'屬性? –

回答

1

也許這有助於

function getValues(array, key) { 
 
    var result = []; 
 
    array.forEach(function (a) { 
 
     a[key] && result.push(a[key]); 
 
    }); 
 
    return result; 
 
} 
 

 
var array = [{ "ghi": { "content": "abc" } }, { "def": { "imgURL": "test.png" } }, { "abc": { "key": "001" } }, { "ghi": { "content": "abc" } }, { "def": { "imgURL": "test.png" } }, { "abc": { "key": "001" } }]; 
 

 
document.write('<pre>' + JSON.stringify(getValues(array, 'ghi'), 0, 4) + '</pre>');