[removed] Getting all existing keys in a JSON array

后端 未结 5 1257
独厮守ぢ
独厮守ぢ 2020-12-17 15:34

I have a JSON array like below:

var jsonArray = [{\"k1\":\"v1\"},{\"k2\":\"v2\"},{\"k3\":\"v3\"},{\"k4\":\"v4\"},{\"k5\":\"v5\"}]

I don\'t

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-17 15:36

    Loop through the object properties, and select the first "real" one (which given your data schema should be the only real one).

    var jsonArray = [{"k1":"v1"},{"k2":"v2"},{"k3":"v3"},{"k4":"v4"},{"k5":"v5"}]
    
    for (var i = 0; i < jsonArray.length; i++) {
        for (var prop in jsonArray[i]) {
            if (jsonArray[i].hasOwnProperty(prop)) {
                var key = prop;
                break;
            }
        }
        alert(key);
    }
    

    See How to loop through items in a js object? for an explanation of why it's important to use hasOwnProperty here.

提交回复
热议问题