Access dynamic key in javascript object

时间:2016-10-15 17:22:10

标签: javascript

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

2 个答案:

答案 0 :(得分:0)

您只需要测试包含子属性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 }

答案 1 :(得分:0)

如果有多个键,请不要使用Object.keys(myObj)[0],因为返回数组的顺序取决于实现。

相反,你应该使用像

这样的东西
var x = getCurrentPropertyName(); // "x"
// ...
myObj[x];

getCurrentPropertyName以某种方式返回所需属性的当前名称。如果您无法知道,那么您的代码就会出现严重问题。