2017-08-11 34 views
0

獲取特定對象我有這樣的:從JSON

'{ 
"Games": [ 
    { "champion": 126, 
     "season": 9 
    }, 
    { 
     "champion": 126, 
     "season": 9 
    }, { 
     "champion": 126, 
     "season": 8 
    }` 

,我想只取冠軍數量我怎麼能做到這一點,這只是從賽季9?

+1

請發佈完整的有效json數據。 –

+0

For循環。你有嘗試過什麼嗎? – scrappedcola

+0

你期望輸出是什麼? '[126,126]'? – PeterMader

回答

1

您可以使用Array.find

const champion = data.Games.find(({season}) => season === 9) 

或ES5

var champion = data.Games.find(function(champion) { 
    return champion.season === 9; 
}); 
1

我相信你必須重複使用條件邏輯來捕獲並返回你正在尋找的任何值在陣列上。

喜歡的東西:

for (var i = 0; i < Games.length; i++) { 
    if (Games[i].season == 9) { 
     return(Games[i].champion); 
    } 
} 
0

使用Array.filter()

var season9 = Games.filter(function(elem) { 
    return (elem.season === 9); 
}); 

或ES6

let season9 = Games.filter(elem => elem.season === 9); 

然後

var champions = season9.map(function(elem) { 
    return elem.champion; 
}) 

或在Es6中

let champions = season9.map(elem => elem.champion); 

console.log(champions) // => [126, 126] 
+0

let result = Games.filter(elem => elem.season == = 9).map(elem => elem.champion); – chrisheyn