[removed] Getting all existing keys in a JSON array

后端 未结 5 1228
独厮守ぢ
独厮守ぢ 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.

    0 讨论(0)
  • 2020-12-17 15:49

    Why don't you use a

    var jsonObject = {"k1":"v1","k2":"v2","k3":"v3","k4":"v4","k5":"v5"}
    

    instead of your

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

    ? Then the solution would be so simple: Object.keys(jsonObject).

    0 讨论(0)
  • 2020-12-17 15:56

    Try this:

    jsonArray.reduce(function(keys, element){ 
        for (key in element) {
           keys.push(key);
        } 
        return keys; 
    },[]);
    

    This should also work for multiple keys in the array objects.

    If you're supporting old browsers that don't have reduce and map, then consider using a shim.

    0 讨论(0)
  • 2020-12-17 16:00
    var id = { "object": "page", "entry": [{ "id": "1588811284674233", "time": 1511177084837, "messaging": [{ "sender": { "id": "1393377930761248" }, "recipient": { "id": "1588811284674233" }, "timestamp": 1511177084553, "message": { "mid": "mid.$cAAX_9pLcfu1mCnGmiVf2Sxd2erI2", "seq": 1882, "text": "a" } }] }] };
    
        function getKey(obj, data) {
    //@author dvdieukhtn@gmail.com
          var data = data || [];
          if (obj) {
            var keys = Object.keys(obj);
            for (var pos in keys) {
              console.log();
              data.push(keys[pos]);
              if ((obj[keys[pos]].constructor === Array)) {
                for (var i = 0; i < obj[keys[pos]].length; i++) {
                  getKey(obj[keys[pos]][i], data);
                }
              }
              else if (obj[keys[pos]].constructor === Object) {
                getKey(obj[keys[pos]], data);
              }
            }
            return data;
          }
        }
        console.log(getKey(id));
    
    0 讨论(0)
  • 2020-12-17 16:01

    Try this:

    var L = jsonArray.length;
    for (var i = 0; i < L; i++) {
        var obj = jsonArray[i];
        for (var j in obj) {
            alert(j);
        }
    }
    

    I've also made some modifications of your current code (like length caching).

    0 讨论(0)
提交回复
热议问题