开发者

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

开发者 https://www.devze.com 2023-02-22 08:39 出处:网络
Say I have this JSON: [ { \"开发者_运维知识库ID\": \"1\", \"title\": \"Title 1\", }, { \"ID\": \"2\",

Say I have this JSON:

[
    {
        "开发者_运维知识库ID": "1",
        "title": "Title 1",
    },
    {
        "ID": "2",
        "title": "Title 2",
    }
]

How would I return the set of key names that recur for each record? In this case, ID, title.

I tried:

$.getJSON('testing.json', function(data) {
  var items = [];
  $.each(data, function(key, val) {
    items.push(key +', ');
  });

  $('<p/>', {
     html: items.join('')
  }).appendTo('#content');
});

without success.

This is a JSON "database", and every "record" has the same keys. I just want a script that will tell me what the keys are, not test whether or not they occur in every entry.


This will give you an array of all the string properties that match across an array of objects. Is that what you are looking for?

$.getJSON('testing.json', function(data) {
    var propertiesThatExistInAll = getPropertiesThatExistInAll(data);
});


var getPropertiesThatExistInAll = function(arr) {
    var properties = $.map(data[0], function (prop, value) {
        return prop;
    });

    var propertiesThatExistInAll = [];

    $.each(properties, function (index, property) {
        var keyExistsInAll = true;

        // skip the first one since we know it has all the properties
        for (var i = 1, len = data.length; i < len; i++) {
            if (!data[i].hasOwnProperty(property)) {
                keyExistsInAll = false;
                break;
            }
        }

        if (keyExistsInAll) {
            propertiesThatExistInAll.push(property);
        }
    });

    return propertiesThatExistInAll;
};


Something like this, perhaps?

items = [];
for (key in jsonobj) {
    if (!itemExists(items, key)) {
        items[items.length] = key
    }
}

function itemExists(items, value) {
    for (i = 0; i < items.length; i++) {
        if (items[i] == value) {
            return true
        }
    }
    return false;
}

Of course, that will return items that exist in any one of the objects, not that exist in all. It's not entirely clear from your question if this is the solution you want.


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消