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

标签 javascript jquery json

假设我有这个 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/

相关文章:

php - 从输入数组中查找数组中相关结果的最快方法

javascript - 包括原语的通用类型保护

javascript - 获取选中选项的id

javascript - html2canvas 未捕获日期选择器

javascript - 在 Facebox 中打开谷歌地图

json - 将 JSON 数据传递到 Spring Controller 时出现错误请求

javascript - 来自 JSON 文件的 AngularJS 缩略图无法加载;如何通过点击缩略图显示大图

javascript - 从 json 到 ul li

javascript - 当再次选择相同条目时,在 HTML <select> 框中触发事件

json - AWS Cloudwatch Log Insights - 按 JSON 日志事件的 JSON 过滤器过滤记录