Get name of key in key/value pair in JSON using jQuery?

前端 未结 3 1467
予麋鹿
予麋鹿 2021-01-13 23:17

Say I have this JSON:

[
    {
        \"ID\": \"1\",
        \"title\": \"Title 1\",
    },
    {
        \"ID\": \"2\",
        \"title\": \"Title 2\",
             


        
3条回答
  •  广开言路
    2021-01-14 00:14

    This can probably be made more efficient/concise, but the function below will do it.

    var testJson = [ {'oi' : 1, 'arf': 2, 'foo' : 0}, {'oi': 5, 'arf': 7}];
    
    function commonKeys(j)
    {
    
        var fillUp = [];
        for(var i in j[0])
           fillUp.push(i);
    
        for(var i = 1; i < j.length; i++)
        {
           var cur = j[i]; var curArr = [];
           for (var i in cur) {curArr.push(i)};
           fillUp = fillUp.filter(function(x) {return (curArr.indexOf(x) != -1);});
        }
    
        return fillUp;
    }
    
    alert(commonKeys(testJson)); //oi,arf (not foo)
    

提交回复
热议问题