JavaScript - Return Matching Name and Value From an Array



Make a function that looks through an array of objects(first argument) and returns an array of all objects that have a 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.


Solution Basic approach


function whatIsInAName(collection, source) {
    var keys = Object.keys(source)
    return collection.filter(function (obj) {
        for (var key of keys) {
            console.log(obj[key])
            if (!obj.hasOwnProperty(key) || obj[key] !== source[key]) {
                return false;
            }
        }
        return true;
    }

    )

}
console.log(whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }],
    { last: "Capulet" }));

Output:


Montague
null
Capulet
[ { first: 'Tybalt', last: 'Capulet' } ]

download android app

Popular javascript Examples









codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube