I am trying to filter the data from an array, but it is throwing an error saying
filter() is not function
Here is the code:
var selectedObject = [];
selectedObject= JSON.stringify(formsDataSource.data());
//console.log(selectedObject);
//var filtered = $.grep(selectedObject, function (el) {
// return el.po_order_no = 18;
//});
//console.log((filtered));
if (selectedObject == undefined) {
alert("Undefined");
} else {
var data= selectedObject.filter(function (element) { return element.po_order_no = "18"; })
alert("" + data);
}
I tried many things but it is still throwing an error. Any help?
In return
statement you have to compare value not assigning the value.
Change:
return element.po_order_no = "18";
To
return element.po_order_no == "18";
Also there might be some issues with the data. Solution with sample data:
var selectedObject = [ { age: 25, po_order_no: "25" }, { age: 22, po_order_no: "18" }, { age: 15, po_order_no: "20" } ]; if (selectedObject == undefined) { console.log("Undefined"); } else { var data= selectedObject.filter(function (element) { return element.po_order_no == "18"; }) console.log(data); }
Few observations :
selectedObject= JSON.stringify(formsDataSource.data());
This statement states that selectedObject is a string. A string does not have a filter()
method.
condition inside filter function should be element.po_order_no == "18"
instead of element.po_order_no = "18"
Solution :
var selectedObject = [ { "po_order_no": 18, "po_order_name": "abc" }, { "po_order_no": 19, "po_order_name": "xyz" } ]; if (selectedObject == undefined) { console.log("Undefined"); } else { var data = selectedObject.filter(element => element.po_order_no == "18") console.log(data); }
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.