0

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'.

2
  • 2
    If the key is always the first (and, perhaps, the only one) in the object, you can do: obj[Object.keys(obj)[0]].b; See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . Alternatively, you can search for the b key: obj[Object.keys(obj).find(i => obj[i].b !== null && obj[i].b !== undefined)].b. Beware that in this second method you should also check the the find result is not null or undefined, otherwise you will have a nullreference error. Commented Sep 21, 2018 at 5:24
  • Possible duplicate of Get the value of an object with an unknown single key in JS Commented Sep 21, 2018 at 6:24

6 Answers 6

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

Use this:

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

Comments

1

You could use Object.values, like so:

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

Comments

1

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

Comments

0

To get the value of b

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.