Skip to content

Instantly share code, notes, and snippets.

@Lelith
Created March 10, 2020 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lelith/e910629d9454fccc7118bc5e880a0f58 to your computer and use it in GitHub Desktop.
Save Lelith/e910629d9454fccc7118bc5e880a0f58 to your computer and use it in GitHub Desktop.
calculate object entries with recursion
function calcObjectLength(myObject, size) {
Object.entries(myObject).forEach(([, value]) => {
if (!isObject(value)) {
console.log('+1');
size += 1;
} else {
console.log('is object');
size += calcObjectLength(value, size);
}
});
return size;
}
try {
const myObject = {
fruit: {
banana: 1,
strawberry: 4,
},
};
const objectLength = calcObjectLength(myObject, 0);
console.log(objectLength);
} catch (e) {
console.log('error');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment