2014-11-20 66 views
-5

我有多個對象的Javascript:遍歷數組獲取對象屬性的每個元素

"status": [ 
    { 
     "feature": "sun", 
     "color": "yellow", 
    }, 
    { 
     "feature": "rain", 
     "color": "grey", 
    }, 

我想每個「功能」返回屬性「顏色」的值 輸出數組將返回:「黃色」和「灰色」

我真的不知道如何下手......

感謝


+0

開始一個循環! – Mathletics 2014-11-20 23:12:22

+0

作爲一個字符串('「黃色灰色」')或作爲一個數組('[「黃色」,「灰色」]')?還是其他什麼東西? – 2014-11-20 23:16:41

回答

1

使用本:

for (var i = 0; i < yourObject.status.length; i++) 
{ 
    console.log(yourObject.status[i].color); 
} 

也許你應該開始at the beginning與循環如何工作的?

+0

謝謝@DavidMüller。我應該在我的問題上更加清楚......對不起。 我實際上試圖根據'功能'返回'顏色'。例如,循環遍歷包含'sun'的元素將返回'黃色'。如果status.feature ===「rain」返回顏色(並且它應該返回'gray' – Eric 2014-11-20 23:34:14

+0

我仍然認爲我不確定你想實現什麼,如果這個特性是「rain」,那麼你想返回這個顏色?在這種情況下? – 2014-11-20 23:39:10

+0

爲一個功能,它應該返回相關的顏色 我試圖根據該功能填充2個不同句子中的2個顏色值,所以它是一個條件的循環 if feature = sun,return color(黃色) 如果功能=下雨,返回顏色(灰色) 我可能沒有看到非常明顯的東西.... – Eric 2014-11-20 23:40:42

0

您可以使用filter

filter返回一個數組,因此,如果您確信只會有一個1:特徵之間的相關性1 /顏色只返回的第一個元素的顏色值:

function getColor(feature) { 
    return obj.status.filter(function (el) { 
    return el.feature === feature; 
    })[0].color; 
} 

getColor('sun'); // yellow 
getColor('rain'); // grey 

DEMO

+0

我很喜歡這個想法@安迪!雖然我得到'obj沒有定義' – Eric 2014-11-21 01:00:15

0

試試這個

var obj = { 
    // ... 
    "status": [ 
     { 
      "feature": "sun", 
      "color": "yellow" 
     }, 
     { 
      "feature": "rain", 
      "color": "grey" 
     } 
    ] 
    // ... 
} 

// Array 
var r1 = obj.status.map(function(obj) {return obj.color}) 

// String 
var r2 = obj.status.map(function(obj) {return obj.color}).join(' ') 

console.log(r1, r2)