简体   繁体   中英

angular2 How to get json id key?

I'm trying to get JSON data from the server. I succeed to make a request that returns the data, but I can't access the collection key. I printed the whole object, and the key exists, but I don't know how to get it. I want to get the key value like "-Ki0NyOnNuPFbtkUSIgs" , here is the console output and my code, any help, please ??

Object printed in the console and Here my code

Use for.in to access the key values of the object like:

var test = {jfhajsk: 'sdgfdg', '-ksdakahcsak': 'asfdwf', 1: 34, 3: 'dsgfg'}
for(var i in test) {
    console.log(i);//Will print jfhajsk, -ksdakahcsak, 1 and 3
    console.log(test[i]);//Will print sdgfdg, asfdwf, 3 and dsgfg
}

If you want to simply print the value of the specified key, just do console.log(variable_name['-Ki0NyOnNuPFbtkUSIgs'])

Since you just have one key in your object you can use Object.keys(row)[0]

 let data = [ {"Ki0NyOnNuPFbtkUSIgs": {date: '', desc: ''}}, {"Ki0NyOnNuPFbtkUS123": {date: '', desc: ''}}, {"Ki0NyOnNuPFbtkUS456": {date: '', desc: ''}} ] for(i = 0; i < data.length; i++) { let row = data[i]; console.log(Object.keys(row)[0]); } 

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