Let's say I have an array with some objects:
var objectsToFind = [
{
name: 'first',
value: 1,
},
{
name: 'second',
value: 2,
},
{
name: 'third',
value: 3,
}
];
And I want to get the objects of this array that match the name property of the previous array's objects:
var findHere = [
{
name: 'fourth',
size: 36,
},
{
name: 'second',
size: 689,
},
{
name: 'third',
size: 47,
},
{
name: 'sixth',
size: 34,
},
];
So the result would be:
var result = [
{
name: 'second',
size: 689,
},
{
name: 'third',
size: 47,
},
];
I made a method that returns the objects using foreach and a find method, but I don't know if this is the most efficent way. Is there a better way to achieve this?
My code to achieve this:
var foundObjects = [];
objectsToFind.forEach(object => {
const found = findHere.find(element => element.name == object.name);
if (found != null) {
foundObjects.push(found);
}
});