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
What am I doing wrong?
If you have a valid json then you don't have to parse it to create a valid json. That should only be done when you have a valid json string like:
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>';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.