简体   繁体   中英

How to find a key and its value in javascript object

I have a javascript object

var obj = {a:{b:'value'}};

where key 'a' is dynamic, key 'b' is constant, so I am not able to get value from obj['a'].

Is there any way to get the value of key 'b' without knowing key 'a'.

You can find all the keys of object using Object.keys(<obj>)

In your case:

key = Object.keys(obj)[0]; // will return "a"

在此处输入图片说明

Use this:

var obj = {a:{b:'value'}};
obj[Object.keys(obj)[0]].b

You could use Object.values , like so:

const obj = { a: { b:'value' } };
Object.values(obj)[0].b // 'value'

Try this,

res = { data: { list: { names: { blk: { cnt: 10 } } } }, test:'test' };
let val = getObjectVal(res, 'cnt')

getObjectVal(data, findKey){
let result = '';
for (let key in data) {
  if (key == findKey)
    result = data[findKey];
  if ((typeof data[key] === "object") && (data[key] !== null)) {
    if (key != findKey)
      result = getObjectVal(data[key], findKey)
  }
}
return result ? result : '';}

To get the value of b

 var obj = {a:{b:'value'}}; console.log(obj[Object.keys(obj)[0]].b) 

 var obj = {a:{b:'value'}}; // Looking for each object variables in obj Object.keys(obj).forEach(function(key){ // Looking for each object variables in the obj[key] Object.keys(obj[key]).forEach(function(key2){ // do what you want if key_2 is b if(key2=='b') console.log(obj[key][key2]) }) }) 

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