[英]Filtering JSON on string attribute with JavaScript
I am trying to filter out all objects based on a string attribute like this: 我试图基于这样的字符串属性过滤掉所有对象:
var data = $.parseJSON(valid_json);
data = data.filter(function (el) {
return (el.name == 'myName');
});
This returns an empty array but comparing integers works: 这将返回一个空数组,但是比较整数是可行的:
var data = $.parseJSON(valid_json);
data = data.filter(function (el) {
return (el.price == 1000);
});
This will get all objects with price = 1000 这将获得价格= 1000的所有对象
What am I doing wrong? 我究竟做错了什么?
If you have a valid json then you don't have to parse it to create a valid json. 如果您具有有效的json,则无需解析它即可创建有效的json。 That should only be done when you have a valid json string like:
仅当您具有有效的json字符串时,才应该这样做:
var jsonstr = '{"name":"Foo", "price":"1000"}'; // this one needs parsing.
Reasons would be for empty Array might be you are targeting the wrong value of a key of the object or the value doesn't exist in the objects you have. 原因可能是空数组,可能是因为您定位的对象键值错误或该对象中不存在该值。
Actually this is working for me: 实际上,这对我有用:
var data = [{name:"Foo", price:1000}, {name:"Bar", price:1000}]; data = data.filter(function (el) { return (el.name == 'Foo'); }); document.body.innerHTML = '<pre>'+ JSON.stringify(data) +'</pre>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.