Keeano Keeano - 5 months ago 7
AngularJS Question

Go through array of objects and return objects that have Ids from an array of Ids

I want to use Lodash to its full capability and i don't see why i could not perform this with Lodash.

I have an array of 38 objects that all have ID's. I also have another array of Id's. I need to map these to the array of objects and have them available in a new array of objects.

I was looking at a solution like this:

var workOrder.model.Lands = [{
ID: "123",
LandArea: "",
LandAreaDescription: "something",
LandAreaNo: 0,
Value: null,
Text: null,
Status: true,
GeoJsonData: null,
GeoJsonCenter: null,
Blocks: Array[3]
},...];

var landIDs = [1, 2, 3, 4];


_.each(workOrder.model.Lands, function(land){
_.each(landIDs, function(id){
console.log(id);
if(land.ID === id){
workOrder.selectedLandArea.push(land);
}
});
});


This does not work and actually returns me all the items in the Lands collections. What is the best solution to get these objects out?

NO JQUERY

Thanks in advance

Update
Added variables to make more clearity

Answer

Demo

Here's the relevant code (assuming objs is the object array and ids is the id array)

_.filter(objs, function(obj) {
  return _.includes(ids, obj.ID);
});

Logically, you're filtering a set based on member keys included in another set.