从JSON获取特定对象[重复]

时间:2023-01-15 16:47:33

This question already has an answer here:

这个问题在这里已有答案:

I have this:

我有这个:

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

And i want only to take champion number that's only from season 9. How can i do that?

而且我只希望获得仅来自第9季的冠军号码。我该怎么做?

3 个解决方案

#1


1  

You can use Array.find:

您可以使用Array.find:

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

or ES5

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

#2


1  

I believe you must iterate over the array with conditional logic to capture and return any values that you are looking for.

我相信你必须使用条件逻辑迭代数组来捕获并返回你正在寻找的任何值。

Something like:

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

#3


0  

Use Array.filter()

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

or in Es6

或者在Es6中

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

then

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

or in Es6

或者在Es6中

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

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

#1


1  

You can use Array.find:

您可以使用Array.find:

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

or ES5

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

#2


1  

I believe you must iterate over the array with conditional logic to capture and return any values that you are looking for.

我相信你必须使用条件逻辑迭代数组来捕获并返回你正在寻找的任何值。

Something like:

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

#3


0  

Use Array.filter()

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

or in Es6

或者在Es6中

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

then

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

or in Es6

或者在Es6中

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

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