JacobPariseau
JacobPariseau

Reputation: 195

Trim JavaScript object to specified properties with matching values

I am trying to verify that an object has a certain set of properties and that their values are of a certain type. I'd like to be able to compare an object to a template like

name: "string",
age: "number",
registered: "boolean"

and return an object with only the fields that match the template.

var object = {
    name: "John McClane",
    age: 45,
    location: "Nakatomi Towers",
    registered: "yes"
}

var document = match(object, template);
console.log(document); 

/* Should return 
{
    name: "John McClane",
    age: 45
}
*/

What are the JavaScript best practices in writing a function like this? I'm not too familiar with the built in methods and iteration so I don't want to go about this the wrong way.

Upvotes: 0

Views: 121

Answers (1)

Phil
Phil

Reputation: 164924

You can use Object.keys to produce an array of template keys, Array.prototype.reduce to iterate over those keys and create a single result object, Object.prototype.hasOwnProperty to test if object has that key and typeof to test the type of object[key].

function match(obj, tpl) {
    return Object.keys(tpl).reduce(function(collection, key) {
        if (obj.hasOwnProperty(key) && typeof obj[key] === tpl[key]) {
            collection[key] = obj[key];
        }
        return collection;
    }, {});
}

Upvotes: 1

Related Questions