假设我有这个 JSON:
[
{
"ID": "1",
"title": "Title 1",
},
{
"ID": "2",
"title": "Title 2",
}
]
我如何返回每条记录重复出现的键名集?在本例中,ID, title
。
我试过:
$.getJSON('testing.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(key +', ');
});
$('<p/>', {
html: items.join('')
}).appendTo('#content');
});
没有成功。
这是一个 JSON“数据库”,每条“记录”都有相同的键。我只想要一个脚本来告诉我键是什么,而不是测试它们是否出现在每个条目中。
最佳答案
这将为您提供一个包含所有匹配对象数组的字符串属性的数组。这就是您要找的吗?
$.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;
};
关于javascript - 使用 jQuery 获取 JSON 中键/值对中的键的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5572708/