使用JSON显示所有具有匹配值的项目的最佳方法是什么?
所以,如果我有这个样本JSON:
{
"AllQuotes": [{
"Quote": "Life is Bad",
"Attributes": {
"StatedYear": 1999,
"smart": true,
"inspiring": false
}
}, {
"Quote": "Life is Good",
"Attributes": {
"StatedYear": 1972,
"smart": false,
"inspiring": true
}
}, {
"Quote": "Let's Party",
"Attributes": {
"StatedYear": 1999,
"smart": false,
"inspiring": true
}
}, {
"Quote": "All is a Game",
"Attributes": {
"StatedYear": 1952,
"smart": true,
"inspiring": false
}
}]
}
使用纯JavaScript,如何从1999年开始引用所有引号?或者所有引用属性inspiring = true?
答案 0 :(得分:2)
“最佳”可以表示任何数量的事情。 我可能会这样做:
var obj = /* ...deserialize the JSON ...*/;
var quotesSince1999 = obj.AllQuotes.filter(function(quote) {
return quote.StatedYear >= 1999;
});
它使用ES5中的Array#filter
函数,该函数可以在较少的旧版浏览器上进行填充。它返回一个数组,其中包含您为其提供的比较器函数的条目,它返回一个truthy值。 quotesSince1999
中的结果是一个数组,其中只包含StatedYear
为>=
1999年的引号。
答案 1 :(得分:0)
因此,要获取特定的节点对象,我们将使用上面的函数。
在此演示: http://jsfiddle.net/csdtesting/nzLnofhz/
<强>实施强>
var data = [{
"AllQuotes": [{
"Quote": "Life is Bad",
"Attributes": {
"StatedYear": 1999,
"smart": true,
"inspiring": false
}
}, {
"Quote": "Life is Good",
"Attributes": {
"StatedYear": 1972,
"smart": false,
"inspiring": true
}
}, {
"Quote": "Let's Party",
"Attributes": {
"StatedYear": 1999,
"smart": false,
"inspiring": true
}
}, {
"Quote": "All is a Game",
"Attributes": {
"StatedYear": 1952,
"smart": true,
"inspiring": false
}
}]
}];
var getSpecificObjects = function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else
if (i == key && obj[i] == val || i == key && val == '') { //
objects.push(obj);
} else if (obj[i] == val && key == '') {
//only add if the object is not already in the array
if (objects.lastIndexOf(obj) == -1) {
objects.push(obj);
}
}
}
return objects;
}
//First one pull all quotes from 1999
var allQuotes1999 = getSpecificObjects(data, "StatedYear", "1999");
console.log(allQuotes1999);
//all quotes with attribute inspiring = true
var allQuotesInspiring = getSpecificObjects(data, "inspiring", true);
console.log(allQuotesInspiring);
您的结果是两个对象只包含具有指定值的节点(*在运行代码后查看控制台):
希望它有所帮助!
答案 2 :(得分:0)
您可以使用此功能在Json By Either Value或Key Or Both中搜索:
function searchJson(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else
if (i == key && obj[i] == val || i == key && val == '') { //
objects.push(obj);
} else if (obj[i] == val && key == ''){
//only add if the object is not already in the array
if (objects.lastIndexOf(obj) == -1){
objects.push(obj);
}
}
}
return objects;
}
您可以像这样使用此功能: 假设obj是你的Json对象,
getObjects(obj,"StatedYear","1999");
它将返回搜索对象, 您也可以像这样使用它来使所有值匹配到“1999”,如下所示:
getObjects(obj,"","1999");
或者像这样将返回所有具有“StatedYear”作为键的对象
getObjects(obj,"StatedYear");