简体   繁体   中英

How to get specific value from JSON

I have JSON, which looks like this:

{ '-KiJz4D0pGYE35HPP-E4': { code: '211', lastname: 'Smith', firstname: 'John' } }

I do know that it will always look this way, ONLY one child in any case. How could I get value '211' stored under code key. Right now I have ugly code with foreach, it even works, but... Why would I use foreach at all if I know there is only one child?

Thanks a lot!

USe Object.keys(obj)[0] to get the first key and then you can get the key code's value from it like

 var obj = { '-KiJz4D0pGYE35HPP-E4': { code: '211', lastname: 'Smith', firstname: 'John' } } console.log(obj[Object.keys(obj)[0]]['code']); 

If

var data = { '-KiJz4D0pGYE35HPP-E4': { code: '211', lastname: 'Smith', firstname: 'John' } };

Then data[Object.keys(data)[0]] will return your inner object

{ code: '211', lastname: 'Smith', firstname: 'John' }

So you easily get code value by data[Object.keys(data)[0]].code

DEMO

 var jsonObj = { '-KiJz4D0pGYE35HPP-E4': { code: '211', lastname: 'Smith', firstname: 'John' } }; var objKey = Object.keys(jsonObj); // return the object key var innerObject = jsonObj[objKey]; // return the inner object var code = innerObject.code; // return the code property value. console.log(code); 

Object.values({ '-KiJz4D0pGYE35HPP-E4': { code: '211', lastname: 'Smith', firstname: 'John' } })[0].code;

只需获取外部对象的第一个值即可...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM