Question
Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching name and value pairs (second argument). Each name and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array.
For example, if the first argument is [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], and the second argument is { last: "Capulet" }, then you must return the third object from the array (the first argument), because it contains the name and its value, that was passed on as the second argument.
My Attempt
function whatIsInAName(collection, source) {
let filteredCollection = collection.filter((item)=>{
return collection[item].indexOf((source[item])> 0);
})
return filteredCollection;
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
My Question
I really struggled to loop through the objects and find the relevant keys and values at the same time. It seems certain functions do not work on objects as they do with Arrays.
Your help is appreciated greatly with fixing this code problem?