Last active
May 6, 2021 03:51
-
-
Save dakshinasd/2301e3ef0a5feb830d5ff98bbc74411c to your computer and use it in GitHub Desktop.
Object Flatner
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
/* | |
Write a function to flatten the following nested object to an array of objects. | |
Your function should be able to handle any level of nesting and it should have better performance. | |
Expected output ex: | |
[ | |
{title: 'Foo', value: 111}, | |
{title: 'Bar', value: 222}, | |
... | |
] | |
*/ | |
// Input object: | |
var obj = { | |
1: { | |
title: 'Foo', | |
value: 111, | |
children: { | |
2: { | |
title: 'Bar', | |
value: 222 | |
} | |
} | |
}, | |
3: { | |
title: 'Baz', | |
value: 333, | |
children: { | |
4: { | |
title: 'Qux', | |
value: 444, | |
children: { | |
5: { | |
title: 'Quux', | |
value: 555 | |
} | |
} | |
} | |
} | |
} | |
} | |
const results = []; | |
const extractValues = (x) => { | |
Object.keys(x).forEach(value => { | |
const tempObj = x[value]; | |
if(tempObj.hasOwnProperty('children')){ | |
extractValues(tempObj.children) | |
} | |
const data = tempValues = { | |
title: tempObj.title, | |
value: tempObj.value | |
} | |
results.push(data); | |
}); | |
} | |
extractValues(obj); | |
console.log('Result', results); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment