How to filter array when object key value is in array

前端 未结 6 830
迷失自我
迷失自我 2020-11-28 08:16

I have an array model as below:

records:[{
    \"empid\":1,
    \"fname\": \"X\",
    \"lname\": \"Y\"
},
{
    \"empid\":2,
    \"fname\": \"A\",
    \"lnam         


        
6条回答
  •  悲哀的现实
    2020-11-28 08:30

    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.​​​​​​

提交回复
热议问题