ezraspectre ezraspectre - 9 months ago 16
Javascript Question

What is the most efficient way for checking if an object parameter has all require properties?

In javascript using an object parameter is my preferred way of working with functions. To check that a function has the required parameters I either (

Solution 1
) loop through all the object parameters properties and throw an error or (
Solution 2
) wait until a required property is needed and throw an error. Solution two seems efficient but I have to throws in multiple places in the function.
Solution 1
seems pragmatic but should probably be a reusable piece of code. Is there another solution I should be looking at?


You can actually do this

var propsNeeded = ["prop1", "prop2", "blah", "blah", "blah"], 
obj = {
  prop1: "Hi"
function hasRequiredProperties(props, obj){
   return Object.keys(obj).sort().join() == propsNeeded.sort().join();
console.log(hasRequiredProperties(propsNeeded, obj)); // false

You can check for single properties like

function hasProperty(propName, obj){
  return obj.hasOwnProperty(propName);