Check if all properties of js object except 3

I have a js object with 50 properties. I want to check if all 47 of them are zero, with the exception of "a1", "a2" and "a3".

myObject = { a1: 'dont-care' a2: 'dont-care' a3: 'dont-care' a4: 'am i null?' a5: 'am i null?' ... a50: 'am i null?' } 
+4
source share
3 answers

You can use Object.keys() with Array.prototype.every() .

DEMO: http://jsfiddle.net/akstE/1/

 var result = Object.keys(myObject) .every(function(key) { switch (key) { // Change these to your actual property names case "a1": case "a2": case "a3": return true; // assuming you don't need to check them at all default: return myObject[key] === null; // `== null` to include `undefined` } }); 

(Requires padding for both methods in older browsers.)

+4
source

What others said about disordered objects is perfectly true, so the concept of "first three" does not make sense.

So what you might want is a function that can be passed to an object and a list of property names, which then checks that any property other than the list in the list is null .

Note that I used === null , so the values ​​must be really null , not just undefined .

 function allButThreeNull(obj, names) { for (var p in obj) { if (obj.hasOwnProperty(p) && names.indexOf(p) == -1) { if (obj[p] !== null) return false; } } return true; } var obj = {one: 'one', two: 'two', three: 'three', four: null, fiv: null}; alert(allButThreeNull(obj, 'one two three'.split(' '))); // true 

Note that you will need shim for Array.prototype.indexOf in browsers that are not compatible with ES5 (e.g. IE 8).

+4
source

How about this:

 var allButFirstThreeAreNull = true; for (var i = 4; i <= 50; i++) { if (myObject['a' + i] !== null) { allButFirstThreeAreNull = false; break; } } 

The key point here is the ability to access a property using some complex expression when using parenthesis notation ( object[property_expression] ). And, of course, you do not need to check other properties if you find one that is not equal to zero; hence the use of break .


Now it turns out that these properties are dynamic. Well, there is one thing to do this:

 var i, l, isValid = true, props = Object.keys(myObject); for (i = 3, l = props.length; i < l; i++) { if (myObject[ props[i] ] !== null) { isValid = false; break; } } 

... except that your first three properties may not actually be the ones you think of. Check this out, for example:

 var foo = { '12': null, booya: 3 '2': null, '3': null, }; 

Writing Object.keys will give you ["2", "3", "12", "booya"] , putting the numeric properties in front (and sorting them by number).

+2
source

Source: https://habr.com/ru/post/1484307/


All Articles