使用jQuery获取JSON中的键/值对中的键名称?

使用jQuery获取JSON中的键/值对中的键名称?

问题描述:

说我有这个JSON:

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

如何返回每个记录重复出现的一组键名?在这种情况下,为ID, title.

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

我尝试过:

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

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

没有成功.

这是一个JSON数据库",每个记录"具有相同的键.我只想要一个脚本,该脚本可以告诉我键是什么,而不是测试它们是否出现在每个条目中.

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;
};