BeeNag BeeNag - 3 months ago 15
Javascript Question

Finding a key in an object by using values from an array

I have an array which is dynamically created by selecting items from a list:

[2, 4]


I also have an array of objects:

[{id: 1, name: "Param1"}, {id: 2, name: "Param2"}, {id: 3, name: "Param3"}, {id: 4, name: "Param4"}]


What I need to do is use the values in the first array to match against the ids in the objects in the second array and return those objects.

Help with this would be much appreciated

Thanks for your time

Answer

You can use this ES6 code, which turns the first array to a Set to allow fast lookup, and then applies the Array filter method, specifically intended for this purpose:

var select = [2, 4];
var data = [{id: 1, name: "Param1"}, {id: 2, name: "Param2"},
            {id: 3, name: "Param3"}, {id: 4, name: "Param4"}]

var selectSet = new Set(select);
var result = data.filter( obj => selectSet.has(obj.id) );

console.log(result);

Comments