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]]
4
  • If at any given time, there is only one key ie., either x, y, a etc you can do myObj[Object.keys(myObj)[0]] Commented Oct 15, 2016 at 17:25
  • What exactly you are getting when you hit the API..? Commented Oct 15, 2016 at 17:29
  • 1
    I'm voting to close this question as off-topic because author has found a solution. Commented Oct 15, 2016 at 17:32
  • @YeldarKurmangaliyev Self answering questions is encouraged. But the solution should be an answer, not be in the question. Commented Oct 15, 2016 at 17:37

2 Answers 2

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 }
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.