Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to check if every property on object is the same recursively in JavaScript?
Let’s say, we are required to write a function, say isSame() that accepts a nested object and returns a boolean depending on the fact whether or not all the keys have the same values. When saying all the keys we mean all the last keys like if a key has a nested object as its value, we are required to traverse to the end of the nested object and check for that value.
For example − If the object is −
const obj = {
a: 1,
b: 1,
c: {
aa: 1
}
};
Then the function should return true as all the end keys have the same value (1). Therefore, let’s write a recursive solution to this problem.
Example
const obj = {
a: 1,
b: 1,
c: {
aa: 3
}
};
const allSame = (obj, value) => {
const keys = Object.keys(obj);
for(let i = 0; i < keys.length; i++){
if(typeof obj[keys[i]] === "object" &&
!Array.isArray(obj[keys[i]])){
return allSame(obj[keys[i]], value);
};
if(!value){
value = obj[keys[i]];
continue;
}
if(obj[keys[i]] !== value){
return false;
};
};
return true;
}
console.log(allSame(obj));
console.log(allSame({ a: 1, b: 1, c: { aa: 1 } }));
console.log(allSame({ a: { x: 1 }, b: 1, c: { aa: 1 } }));
console.log(allSame({ a: 1, b: 1, c: { aa: 2 } }));
Output
The output in the console will be −
false true true false
Advertisements