我从来没有遇到麻烦从网址或任何像这样建立的东西读取json:
{ success: true, name: 'Dekirai', clan: null, level: 7, exp: 3193, playtime: 0, tdrate: 0, kdrate: 0, matches_played: 0, matches_won: 0, matches_lost: 0, last_online: '2018-03-02T23:00:00.000Z', views: 1, favorites: 0, fame: 0, hate: 0 }
但是json我现在在这里使用了方括号,如下所示:
[ { id: 23, name: 'AeriaGames Login', player_limit: -1, player_online: -1, state: 2, last_update: '2018-02-14T16:22:28.000Z' }, { id: 1, name: 'Auth', player_limit: -1, player_online: -1, state: 2, last_update: '2018-03-03T14:17:22.000Z' }, { id: 10, name: 'English 1 (Europe)', player_limit: 4000, player_online: 871, state: 2, last_update: '2018-03-03T14:17:22.000Z' }, { id: 11, name: 'English 2 (Europe)', player_limit: 4000, player_online: 48, state: 2, last_update: '2018-03-03T14:17:22.000Z' }, { id: 12, name: 'English 3 (North America)', player_limit: 4000, player_online: 54, state: 2, last_update: '2018-03-03T14:17:22.000Z' } ]
我现在的问题是:
如何从“id:10”中读取“player_online”值?
您可以使用find查找player_online的值。
var data = [{
id: 23,
name: 'AeriaGames Login',
player_limit: -1,
player_online: -1,
state: 2,
last_update: '2018-02-14T16:22:28.000Z'
},
{
id: 1,
name: 'Auth',
player_limit: -1,
player_online: -1,
state: 2,
last_update: '2018-03-03T14:17:22.000Z'
},
{
id: 10,
name: 'English 1 (Europe)',
player_limit: 4000,
player_online: 871,
state: 2,
last_update: '2018-03-03T14:17:22.000Z'
},
{
id: 11,
name: 'English 2 (Europe)',
player_limit: 4000,
player_online: 48,
state: 2,
last_update: '2018-03-03T14:17:22.000Z'
},
{
id: 12,
name: 'English 3 (North America)',
player_limit: 4000,
player_online: 54,
state: 2,
last_update: '2018-03-03T14:17:22.000Z'
}
]
var getPlayerOnline = data.find(obj => obj.id === 12).player_online
console.log(getPlayerOnline)
let player_online = yourObject.find(el => el.id === 10).player_online
你可以使用filter
方法。这将返回匹配属性的数组。然后使用dot
运算符获取属性值
var x = [{
id: 23,
name: 'AeriaGames Login',
player_limit: -1,
player_online: -1,
state: 2,
last_update: '2018-02-14T16:22:28.000Z'
},
{
id: 1,
name: 'Auth',
player_limit: -1,
player_online: -1,
state: 2,
last_update: '2018-03-03T14:17:22.000Z'
},
{
id: 10,
name: 'English 1 (Europe)',
player_limit: 4000,
player_online: 871,
state: 2,
last_update: '2018-03-03T14:17:22.000Z'
},
{
id: 11,
name: 'English 2 (Europe)',
player_limit: 4000,
player_online: 48,
state: 2,
last_update: '2018-03-03T14:17:22.000Z'
},
{
id: 12,
name: 'English 3 (North America)',
player_limit: 4000,
player_online: 54,
state: 2,
last_update: '2018-03-03T14:17:22.000Z'
}
]
var getPlayerOnline = x.filter(function(item) {
return item.id === 10 // will return object where id is 10
})[0].player_online;
console.log(getPlayerOnline)