我正在尝试过滤大型json数据集,我想知道如何垂直选择json对象。
Lat's采取这个小例子,我想选择所有书籍作者名称包含'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') " ) ;
你有两个方面的问题,解决这个问题的最快方法是什么,因为我拥有庞大的数据集?
答案 0 :(得分:3)
您可以使用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(包括旧版浏览器的垫片)
答案 1 :(得分:0)
答案 2 :(得分:0)
您可以使用filter
:
data.filter(function(book) {
return /Evelyn/.test(book.author);
});
答案 3 :(得分:0)
contains
运算符在这里不起作用,你必须在这里使用indexOf函数。
以下代码应该可以正常工作
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
}];
data.forEach(function(args){
if(args.author.indexOf('Evelyn') >= 0){
console.log(args);
}
});