Junie
Junie

Reputation: 437

How to find the value of a dynamic key 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'.

Upvotes: 0

Views: 345

Answers (6)

Sabash
Sabash

Reputation: 152

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 : '';}

Upvotes: 1

n1stre
n1stre

Reputation: 6086

You could use Object.values, like so:

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

Upvotes: 1

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])
 })
})

Upvotes: 0

Raj Nandan Sharma
Raj Nandan Sharma

Reputation: 3862

To get the value of b

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

Upvotes: 0

Avinash
Avinash

Reputation: 2195

Use this:

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

Upvotes: 1

Aagam Jain
Aagam Jain

Reputation: 1546

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

In your case:

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

enter image description here

Upvotes: 4

Related Questions