Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter array when object key value is in array

I have an array model as below:

records:[{     "empid":1,     "fname": "X",     "lname": "Y" }, {     "empid":2,     "fname": "A",     "lname": "Y" }, {     "empid":3,     "fname": "B",     "lname": "Y" }, {     "empid":4,     "fname": "C",     "lname": "Y" }, {     "empid":5,     "fname": "C",     "lname": "Y" } ] 

Now I have an array of empid's [1,4,5].

So now I need to filter the first array which contains all the keys in my second.

Output:

records:[{     "empid":1,     "fname": "X",     "lname": "Y" }, {     "empid":4,     "fname": "C",     "lname": "Y" }, {     "empid":5,     "fname": "C",     "lname": "Y" } ] 

I can do this using a forEach loop in angular but as I have more than 100 records in my model object. I need a suggestion on how to handle this in much better way.

I am thinking of creating a custom filter, but what is your take on it.(If yes please provide sample code to achieve this).

like image 221
krsnaadi Avatar asked Mar 05 '16 17:03

krsnaadi


People also ask

How do you filter objects with keys?

JavaScript objects don't have a filter() method, you must first turn the object into an array to use array's filter() method. You can use the Object. keys() function to convert the object's keys into an array, and accumulate the filtered keys into a new object using the reduce() function as shown below.

How do you filter a key in an array?

If you want to filter array based on the array key, We need to use ARRAY_FILTER_USE_KEY as third parameter of array function array_filter. $get_key_res = array_filter($array,"get_key",ARRAY_FILTER_USE_KEY );


1 Answers

You can do it with Array.prototype.filter(),

var data = { records : [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }] } var empIds = [1,4,5] var filteredArray = data.records.filter(function(itm){   return empIds.indexOf(itm.empid) > -1; });  filteredArray = { records : filteredArray }; 

If​ the ​callBack​ returns a ​true​ value, then the ​itm​ passed to that particular callBack will be filtered out. You can read more about it here.​​​​​​

like image 58
Rajaprabhu Aravindasamy Avatar answered Oct 09 '22 22:10

Rajaprabhu Aravindasamy