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

eth*_*han 4 javascript jquery json

说我有这个JSON:

[
    {
        "ID": "1",
        "title": "Title 1",
    },
    {
        "ID": "2",
        "title": "Title 2",
    }
]
Run Code Online (Sandbox Code Playgroud)

如何返回每条记录重复出现的一组密钥名称?在这种情况下,ID, title.

我试过了:

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

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

没有成功.

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

Eli*_*Eli 5

这将为您提供一个数组,其中包含与对象数组匹配的所有字符串属性.那是你在找什么?

$.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;
};
Run Code Online (Sandbox Code Playgroud)