开发者

JavaScript/JSON: Get unknown property of an object

开发者 https://www.devze.com 2023-03-02 11:04 出处:网络
开发者_如何学JAVAIf I have a JSON object like this: { \"message\": { \"name\": { \"stringLengthTooShort\": \"blub\" }
开发者_如何学JAVA

If I have a JSON object like this:

{
    "message": {
        "name": { "stringLengthTooShort": "blub" }
    }
}

The name of the property (here) stringLengthTooShort is changing every time, how could I simply just get the child property of name with JS? At the moment I have message.name but how could I get now the child of it?


if it's always the first property of message.name, you could do something like:

var keys = [];
for (var l in message.name) {
  if (message.name.hasOwnProperty(l)){
    keys.push(l);
  }
}
//=>first property value should now be in message.name[keys[0]]);
//  (its label is keys[0])

Edit: nine years after this answer all modern browsers support es20xx, so it's safe to use:

const obj = {
    "message": {
        "name": { "stringLengthTooShort": "blub" }
    }
};

console.log(Object.keys(obj.message.name)[0]);

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号