我正在过滤一个大型 json 数据集,我想知道如何垂直选择 json 对象。
举个小例子,我想选择所有作者姓名包含“Evelyn”的书籍
data= [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price":8
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 8
},
{ "category": "fiction",
"author": "Evelyn Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
结果我应该得到:
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 8
},
{ "category": "fiction",
"author": "Evelyn Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
我可以这样做吗:
$.each(data,function(i,el)
{
var newdata;
if (data.author.contains('Evelyn')) newdata.push()
});
另一种方式:
data.where( "( n, i ) => n.author.contains('Evelyn') " ) ;
您知道这两种方式的问题出在哪里吗?因为我有一个巨大的数据集,解决这个问题的最快方法是什么?
最佳答案
您可以使用Array.filter
:
var filtered = data.filter(function(a){return +(a.price) >= 8;}
或者在author
字段上过滤:
var filtered = data.filter(function(a){return /evelyn/i.test(a.author);});
// now [filtered] contains the objects from [data]
// where 'author' contains 'Evelyn'
// filtered.length => 2
// filtered[0].category => 'fiction'
MDN filter documentation (包括适用于旧版浏览器的填充程序)
关于javascript - 根据条件选择 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20370318/