jquery 获取键值对中最大值_使用jQuery获取JSON中的键/值对中的键名称?

Say I have this 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.

I tried:

$.getJSON('testing.json', function(data) {

var items = [];

$.each(data, function(key, val) {

items.push(key +', ');

});

$('

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.

解决方案

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;

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值