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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5572708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:39:20  来源:igfitidea点击:

Get name of key in key/value pair in JSON using jQuery?

javascriptjqueryjson

提问by ethan

Say I have this JSON:

假设我有这个 JSON:

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

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

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

I tried:

我试过:

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

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

without success.

没有成功。

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.

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

回答by Eli

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

回答by crazy2be

Something like this, perhaps?

像这样的东西,也许?

items = [];
for (key in jsonobj) {
    if (!itemExists(items, key)) {
        items[items.length] = key
    }
}

function itemExists(items, value) {
    for (i = 0; i < items.length; i++) {
        if (items[i] == value) {
            return true
        }
    }
    return false;
}

Of course, that will return items that exist in any oneof the objects, not that exist in all. It's not entirely clear from your question if this is the solution you want.

当然,这将返回存在于任何一个对象中的项目,而不是全部存在的项目。如果这是您想要的解决方案,您的问题并不完全清楚。

回答by jon_darkstar

This can probably be made more efficient/concise, but the function below will do it.

这可能会更高效/简洁,但下面的函数会做到这一点。

var testJson = [ {'oi' : 1, 'arf': 2, 'foo' : 0}, {'oi': 5, 'arf': 7}];

function commonKeys(j)
{

    var fillUp = [];
    for(var i in j[0])
       fillUp.push(i);

    for(var i = 1; i < j.length; i++)
    {
       var cur = j[i]; var curArr = [];
       for (var i in cur) {curArr.push(i)};
       fillUp = fillUp.filter(function(x) {return (curArr.indexOf(x) != -1);});
    }

    return fillUp;
}

alert(commonKeys(testJson)); //oi,arf (not foo)