Reputation: 437
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
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
Reputation: 6086
You could use Object.values
, like so:
const obj = { a: { b:'value' } };
Object.values(obj)[0].b // 'value'
Upvotes: 1
Reputation: 1540
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
Reputation: 3862
To get the value of b
var obj = {a:{b:'value'}};
console.log(obj[Object.keys(obj)[0]].b)
Upvotes: 0
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"
Upvotes: 4