0

Im not sure if im asking the right question, but here it goes. I am hitting an API and getting an javascript object that looks like the following

x: {
  id: 1,
  username: 'Ryan',
  picture: 151
}

Im storing this object in a myObj const. I want to access the data inside x, but the issue is each time I hit the API x changes names. The object keys inside x remain the same, but sometimes x is y, a, l, b, etc.

Right now Im trying

myObj.x

but once x is y, I would have to change it to myObj.y instead. How can I access the properties inside this dynamic object?

SOLUTION:

myObj[Object.keys(myObj)[0]]
Munsterberg
  • 758
  • 4
  • 17
  • 37

2 Answers2

0

You just need to test the property which contains a subproperty id

var obj = {
  a: {
      id: 1,
      username: 'Ryan',
      picture: 151
    },
  b: {
      ident: 2,
      firstName: 'jim',
      movie: 321
    }
};

var x = obj[Object.keys(obj).filter(item => obj[item].id)];
console.log(x); // { id: 1, username: 'Ryan', picture: 151 }
kevin ternet
  • 4,514
  • 2
  • 19
  • 27
-1

Do not use Object.keys(myObj)[0] if there is more than one key, because the order of the returned array is implementation dependent.

Instead, you should use something like

var x = getCurrentPropertyName(); // "x"
// ...
myObj[x];

Where getCurrentPropertyName somehow returns the current name of the desired property. If you have no way to know that, you have a serious problem with your code.

Oriol
  • 274,082
  • 63
  • 437
  • 513