0

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.

4
  • There are no specific 'best practices' for this. If writing this, using in and typeof would probably be helpful starts - ignoring edge cases. There is no built-in feature for such a test. There are probably existing 3rd party libraries (FSVO) under the guise of 'JSON schema validation' or similar. Commented Jan 4, 2016 at 1:24
  • Are you okay with using a library like Underscore or LoDash? Or do you want to stick to plain JavaScript? Commented Jan 4, 2016 at 1:27
  • Programmers.SE is for whiteboarding design problems. Commented Jan 4, 2016 at 1:33
  • Something like this Commented Jan 4, 2016 at 1:33

1 Answer 1

1

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;
    }, {});
}
Sign up to request clarification or add additional context in comments.

2 Comments

Suggestion: typeof might not work for all cases, for instance null. Something like this should probably be the type matching function
@nem true. If OP wants to test for types like Array, typeof isn't going to cut it either but given the sample of "string", "number" and "boolean", it should suffice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.