Getting first JSON property

前端 未结 5 1959
闹比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 06:00

    Great question. I don't know of any way besides iterating in a for-in loop. You only need to iterate once though. For safety, ensure it's a known property [more info].

    for (var propName in jsonObj) {
        if (jsonObj.hasOwnProperty(propName)) {
            return propName;    // or do something with it and break
        }
    }
    

    Edited to be extra clear that you're iterating over the property names, not their values.

提交回复
热议问题