Last active
June 20, 2018 11:42
-
-
Save jsphkhan/1b08503fe1c7fb156f3f510994ca86b0 to your computer and use it in GitHub Desktop.
Flatten an object using JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Given an input object | |
var obj = { | |
a: { | |
b: 1, | |
c: 1, | |
d: { | |
e: 1, | |
f: 1 | |
} | |
}, | |
g: 2, | |
h: { | |
i: 2, | |
j: 3 | |
} | |
}; | |
Flatten it so that the output is | |
newObj = { | |
a: 3 | |
b: 1 | |
c: 1 | |
d: 2 | |
e: 1 | |
f: 1 | |
g: 2 | |
h: 2 | |
i: 2 | |
j: 3 | |
} | |
*/ | |
var newObj = {}; | |
function flatten(obj) { | |
for(var key in obj) { | |
if(typeof obj[key] === 'object') { //key is an object, so process again | |
newObj[key] = Object.keys(obj[key]).length; | |
flatten(obj[key]); | |
} else { | |
newObj[key] = obj[key]; //primitive value, just copy | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment