Search code examples
javascripttypescriptunderscore.jslodash

Find array of objects from keys array


I have an array of object

let objList = [
 {
  id:10,
  ...
 },

 {
  id: 12,
  ...
 },

 {
  id: 13,
  ...
 },

 ...
];

and I wanted to filter out all the objects whose IDs are in another array

let keyList = [10, 13];

Expected output:

[
 {
  id: 10,
  ...
  },

 {
  id: 13,
  ...
 }
]

Note:

The req. is in an Angular 7 application and I use Lodash library as well.

I tried:

objList.filter(eachObj => keysList.forEach(
          eachID => {
            eachID == eachObj['id']
          }
        ))

and

find(ObjList, eachObj => {

          return eachObj['id'] === keysList.map(eachID => {
            return eachID;
          })
        })

Solution

  • You can use filter:

    objList = objList.filter(element => keyList.indexOf(element.id) > -1);