How to check if every property on object is the same recursively in JavaScript
{
a:1,
b 1,
c:{
aa:1,
},
};
would be true
if we replaced aa: 1 with aa: 2 we'd want to return false.
How to check if every property on object is the same recursively in JavaScript
{
a:1,
b 1,
c:{
aa:1,
},
};
would be true
if we replaced aa: 1 with aa: 2 we'd want to return false.
Here's one way to do it, just iterating recursively with an IIFE, and putting all the values in an array, and then comparing them
var obj = {
a: 1,
b: 1,
c:{
aa:1
}
};
function isAllSame(o) {
var values = [];
(function rec(obj) {
Object.keys(obj).forEach(function(key) {
if (typeof obj[key] === 'object') return rec(obj[key]);
values.push(obj[key])
})
})(o);
return values.every( x => values[0] === x);
}
console.log( isAllSame(obj) );
You could take an object for checking the value, because the value is kind of backtracked to the calling function by using a reference.
The value to check is wrapped in an object, which allows to use it in all recursive called functions, even in the first, where no real value is first available, because of having objects with nested properties.
At the first call value is checked and if falsey, then it is initialised with an object. If the first real value is found, then it is used as kind of back propagation with an object and it can be used in any running calls of check.
Array#every is used,
The
every()method tests whether all elements in the array pass the test implemented by the provided function.
to exit early if a value does not match the first found value. Thi is the exit condition for the callback and the value to give back.
function check(object, value) {
value = value || {};
return Object.keys(object).every(function (k) {
if (object[k] && typeof object[k] === 'object') {
return check(object[k], value);
}
if (!('value' in value)) {
value.value = object[k];
return true;
}
return object[k] === value.value;
});
}
console.log(check({ a: 1, b: 1, c: { aa: 1 } }));
console.log(check({ a: { x: 1 }, b: 1, c: { aa: 1 } }));
console.log(check({ a: 1, b: 1, c: { aa: 2 } }));
*works now
var obj = {
a: 1,
b: 1,
c:{
aa:1
}
};
function checkifEqual(var object, var recent)
{
for( var x = 0; x < object.length; x++)
{
if(x == 0 && recent == null)
{
recent = object[x];
continue;
}
if( typeof(object[x]) !== 'object' && object[x] == recent)
{
continue;
}
else if(typeof(object[x]) === 'object')
{
if( checkifEqual(object[x],recent))
{
continue;
}
else
{
return false;
}
}
else
{
return false;
}
}
return true;
}
console.log(checkifEqual(obj,null));
on first call you would pass checkifEqual(Object,null)