Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
61
rated 0 times [  63] [ 2]  / answers: 1 / hits: 23910  / 11 Years ago, sat, december 14, 2013, 12:00:00

Let's say I have an object named a, how could I check that a has a specific list of multiple properties in shorthand, I think it can be done using in logical operator,



Something like this:



var a = {prop1:{},prop2:{},prop3:{}};
if ({1:prop1,2:prop2,3:prop3} in a)
console.log(a has these properties:'prop1, prop2 and prop3');


EDIT



If plain javascript can't help, jQuery will do, but i prefer javascript



EDIT2



Portability is the privilege


More From » jquery

 Answers
18

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;
};
}

[#73736] Thursday, December 12, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
skyler

Total Points: 646
Total Questions: 119
Total Answers: 96

Location: Bonaire
Member since Wed, Mar 29, 2023
1 Year ago
skyler questions
;