Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS JSON Array filtering

I have used Node to retrieve a set of results from SQL and they're returned like this;

[
   {
   "event_id": 111111,
   "date_time": "2012-11-16T01:59:07.000Z",
   "agent_addr": "127.0.0.1",
   "priority": 6,
   "message": "aaaaaaaaa",
   "up_time": 9015040,
   "hostname": "bbbbbbb",
   "context": "ccccccc"
},
   {
   "event_id": 111112,
   "date_time": "2012-11-16T01:59:07.000Z",
   "agent_addr": "127.0.0.1",
   "priority": 6,
   "message": "aaaaaaaaa",
   "up_time": 9015040,
   "hostname": "bbbbbbb",
   "context": "ddddddd"
},
]

There are usually a lot of entries in the array and I need to efficiently filter the array to show only the entries that have a context of "ccccccc". I've tried a for loop, but it's incredibly slow.

Any suggesstions?

like image 421
user2039280 Avatar asked May 27 '26 12:05

user2039280


2 Answers

There is a very simple way of doing that if you want to do that in node and don't want to use sql for that you can user javascript built-in Array.filter function.

var output = arr.filter(function(x){return x.context=="ccccccc"}); //arr here is you result array

The ouput array will contains only objects having context "ccccccc".

like image 82
khurrum qureshi Avatar answered May 30 '26 06:05

khurrum qureshi


Another way of doing what Khurrum said, is with the arrow function. It has the same result but some people prefer that notation.

var output = arr.filter(x => x.context == "ccccccc" );
like image 20
viga11 Avatar answered May 30 '26 07:05

viga11



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!