Reputation: 2871
I am using node.js to receive hundreds of data objects from an external API in JSON such as below:
[
{
"ID": "6548532",
"Status": "active",
"Updated": "2014-11-24T07:32:04-07:00",
"created": "2014-09-15T19:42:37-07:00",
"URL": "www.example.com",
"Categories": [
"cat-a",
"cat-b"
],
"Price": "10.00"
},
{
"ID": "8558455",
"Status": "inactive",
"Updated": "2014-10-24T07:32:04-07:00",
"created": "2014-09-15T19:42:37-07:00",
"URL": "www.example.com",
"Categories": [
"cat-c",
"cat-r"
],
"Price": "20.00"
}
....
]
I would like to separate out the objects so that I can write only objects which have "Status": "active"
to my database. I am aware that I can do this using string operations before using JSON.parse
but I am wondering if there is a better way to split up a JSON file into the objects it contains and leave them in an array which I can then process.
Upvotes: 2
Views: 9876
Reputation: 6675
You should be able to use Array.prototype.filter
on the array returned by JSON.parse
:
var objects = JSON.parse(input);
objects.filter(function (el) {
return el.status === "active";
});
Upvotes: 2
Reputation: 3387
You should not use string operations for this, or do anything to it before parsing it with JSON.parse
, unless you feel like writing your own complete JSON parsing logic.
Just parse it and then remove the objects that don't have Status: "active"
:
var objects = JSON.parse(JSON_data);
var filtered_objects = objects.filter(function(el) {return (el["Status"] == "active");});
Upvotes: 3
Reputation: 642
After you parse the JSON into a Javascript object, you can use the filter function to remove the elements where "Status"
does not equal "active"
:
var responseArray = JSON.parse(responseData),
filteredArray = responseArray.filter(
function (obj) {
return obj.Status == "active";
});
// Use filteredArray
Upvotes: 5