Getting first JSON property

前端 未结 5 1972
闹比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:54

    There isn't a "first" property. The properties of an object are unordered.

    You can get whatever one the JS engine decides to provide first with a loop.

    function maybe_first_in_object(ob) {
        for (var props in ob) {
            return prop;
        }
    }
    

    … but if the order matters, use an array not an object.

提交回复
热议问题