使用jQuery获取JSON中的键/值对中的键名称? [英] Get name of key in key/value pair in JSON using jQuery?

查看:208
本文介绍了使用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;
};

这篇关于使用jQuery获取JSON中的键/值对中的键名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆