Getting first JSON property

前端 未结 5 1961
闹比i
闹比i 2020-12-15 05:07

Is there a way to get the name of the first property of a JSON object?

I\'d like to do something like this:

var firstProp = jsonObj[0];
<
5条回答
  •  死守一世寂寞
    2020-12-15 05:40

    The order of the properties of an object are not guaranteed to be the same as the way you put them in. In practice, however, all major browsers do return them in order. So if you're okay with relying on this...

    var firstProp;
    for(var key in jsonObj) {
        if(jsonObj.hasOwnProperty(key)) {
            firstProp = jsonObj[key];
            break;
        }
    }
    

    Also note that there's a bug in Chrome regarding the ordering, in some edge cases it doesn't order it in the way they were provided. As far as it changing in the future, the chances are actually pretty small as I believe this is becoming part of the standard so if anything support for this will only become official.

    All things considered, though, if you really, really, absolutely, positively, want to be sure it's going to be in the right order you need to use an array. Otherwise, the above is fine.

    Related question: Elements order - for (… in …) loop in javascript

提交回复
热议问题