How To Check If An Object Property Has Been Set In A User Supplied Parameter? [closed]

StackOverflow https://stackoverflow.com/questions/23323439

  •  10-07-2023
  •  | 
  •  

Pregunta

I have a method that takes an object as a parameter and all expected properties are required else I want to throw an error. Whats the best practice for doing this. Can it be done easily with Underscore's _.map or something similar?

By "required" I mean anything but null and undefined.

¿Fue útil?

Solución

You might use _.intersection and Object.keys:

function yourFunc(args) {
    if(_.intersection(["name", "secondName", "age"], Object.keys(args)).length != 3) {
        throw Error("Check your arguments: something is missing!");
    }
}

Note that this kind of check will work if arguments aren't instantited from a prototype. From Mozilla Development network:

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Otros consejos

Here's a way to do it without a library, using just the standard JavaScript array .some() method:

function yourFunction(params) {
   if (params == null || typeof params != "object") {
      throw "Missing parameters - 'params' must be an object";
   } else if (["rp1", "rp2", "etc"].some(function(p) { return !(p in params); })) {
      throw "Missing parameter";
   }

   // if we got this far the parameters were all supplied
};

...Where the values in the array ("rp1", etc) are the names of the required parameters.

If you want to support pre-IE9 then you could use whatever Underscore's equivalent method is.

You can get all properties using Object.keys(your_object). This will produce an array of object keys.

var requiredKeys = [....];

function isCorrectObject(obj, testForTruthy) {
  return _(requiredKeys).every(function(key) {
    return obj[key] || (!testForTruthy && _(obj).has(key));
  });
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top