根据条件选择JSon对象
Select JSon objects based on criteria
我正在过滤一个大型json数据集,我想知道如何垂直选择json对象。
Lat以这个小例子为例,我想选择所有作者名字包含"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过滤器文档(包括旧浏览器的填充程序)
你试过这个吗?我已经在我的一些项目中使用过它,真的可以推荐它。http://www.hugoware.net/projects/jlinq
您可以使用filter
:
data.filter(function(book) {
return /Evelyn/.test(book.author);
});
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);
}
});
相关文章:
- jQuery匹配JSON对象的部分文本
- 如何在Javascript中将JSon对象转换为数组
- 我可以在json对象中添加一个函数吗
- 使用JS将数组转换为json对象
- 如何为json对象中的段发送array[]
- 将JSON对象传递给angular指令
- 更改JSON对象的结构
- 访问JSON对象内部的数组元素
- 在ejs-partial中对JSON对象进行迭代
- 遍历 JSON 对象并检查 URL 是否以某个值结尾
- 访问嵌套JSON对象的键,其中键是动态的
- json对象中缺少对象循环
- 发送json对象或使用express路由呈现视图
- 在play2框架中向json对象添加下拉列表项
- 元素名称上带有短划线 (-) 字符的 Json 对象
- autocomplete不接受源的json对象
- 如何在javascript中创建动态json对象
- 在使用客户端脚本时拾取JSON对象
- 如何通过json对象数组为嵌套对象赋值
- 构造JSON对象