Skip to content

Instantly share code, notes, and snippets.

@dakshinasd
Last active May 6, 2021 03:51
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 dakshinasd/2301e3ef0a5feb830d5ff98bbc74411c to your computer and use it in GitHub Desktop.
Save dakshinasd/2301e3ef0a5feb830d5ff98bbc74411c to your computer and use it in GitHub Desktop.
Object Flatner
/*
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