I've got this json object via an API.
var servers = {
'd22ab1': {
condition: 'autorebooted',
name: 'acb1'
},
'6946e0': {
condition: 'online',
name: 'abc2'
}
}
for (var server in servers) {
console.log(server.condition);
}
I'm trying to get the condition value but my for loop doesn't work as i expected. what am I missing? Thank you!!!
You need to access via server
key as you iterate over keys.
var servers = { 'd22ab1': { condition: 'autorebooted', name: 'acb1' }, '6946e0': { condition: 'online', name: 'abc2' } } for (var server in servers) { console.log(servers[server].condition); }
Or you can use Object.values
, which returns values of each property.
var servers = { 'd22ab1': { condition: 'autorebooted', name: 'acb1' }, '6946e0': { condition: 'online', name: 'abc2' } } Object.values(servers).forEach(item => console.log(item.condition));
servers
is not iterable, use Object.values
Object.values( servers ).forEach( s => console.log( s.condition ) )
Demo
var servers = { 'd22ab1': { condition: 'autorebooted', name: 'acb1' }, '6946e0': { condition: 'online', name: 'abc2' } }; Object.values( servers ).forEach( s => console.log( s.condition ) )
Use Object.keys on server to get all the keys. Then iterate over the keys and get conditions from each.
var servers = { 'd22ab1': { condition: 'autorebooted', name: 'acb1' }, '6946e0': { condition: 'online', name: 'abc2' } } let conditions = Object.keys(servers).map(key => servers[key].condition); console.log(conditions)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.