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

前端 未结 3 1485
予麋鹿
予麋鹿 2021-01-13 23:17

Say I have this JSON:

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


        
3条回答
  •  没有蜡笔的小新
    2021-01-14 00:09

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

提交回复
热议问题