Check if object has a set of properties in javascript
Like this:
var testProps = ['prop1', 'prop2', 'prop3', 'prop4'];
var num = -1, outA;
for(var i in a){
if(i === testProps[++num])outA[num] = i;
}
console.log('properties in a: '+outA.join(', '));
Use Array.reduce like this:
var testProps = ['prop1', 'prop2', 'prop3'];
var a = {prop1:{},prop2:{},prop3:{}};
var result = testProps.reduce(function(i,j) { return i && j in a }, true);
console.log(result);
This is where the underscore.js library really shines. For instance it provides an already poly-filled every()
method as suggested in a comment to p.s.w.g.'s answer: http://underscorejs.org/#every
But there's more than one way to do it; the following, while more verbose, may also suit your needs, and exposes you to more of what underscore can do (e.g. _.keys and _.intersection)
var a = {prop1:{},prop2:{},prop3:{}};
var requiredProps = ['prop1', 'prop2', 'prop3'];
var inBoth = _.intersection(_.keys(a), requiredProps);
if (inBoth.length === requiredProps.length) {
//code
}
The simplest away is to use a conventional &&
:
if ("prop1" in a && "prop2" in a && "prop3" in a)
console.log("a has these properties:'prop1, prop2 and prop3'");
This isn't a 'shorthand', but it's not that much longer than what you've proposed.
You can also place the property names you want to test in an array and use the every
method:
var propertiesToTest = ["prop1", "prop2", "prop3"];
if (propertiesToTest.every(function(x) { return x in a; }))
console.log("a has these properties:'prop1, prop2 and prop3'");
Note however, that this was introduced in ECMAScript 5, so it is not available on some older browsers. If this is a concern, you can provide your own version of it. Here's the implementation from MDN:
if (!Array.prototype.every) {
Array.prototype.every = function(fun /*, thisp */) {
'use strict';
var t, len, i, thisp;
if (this == null) {
throw new TypeError();
}
t = Object(this);
len = t.length >>> 0;
if (typeof fun !== 'function') {
throw new TypeError();
}
thisp = arguments[1];
for (i = 0; i < len; i++) {
if (i in t && !fun.call(thisp, t[i], i, t)) {
return false;
}
}
return true;
};
}