Skip to content

Instantly share code, notes, and snippets.

@cedrickvstheworld
Created February 10, 2020 04:50
Show Gist options
  • Save cedrickvstheworld/0ec85dfeda2c403fc1f40f1fd0887829 to your computer and use it in GitHub Desktop.
Save cedrickvstheworld/0ec85dfeda2c403fc1f40f1fd0887829 to your computer and use it in GitHub Desktop.
flatten js object to Depth = 1
let oldData = {
age: 3,
name: "dudeson",
height: 70,
type: 3,
address: {
city: 'Manila',
street: 'street 66',
province: {
district: {
number: 'IV',
name: 'Nueva Ecija'
}
}
},
this_shit: [3,3,4 ,4]
}
const flattenObject = (obj) => {
let flattened = {}
Object.keys(obj).forEach((key) => {
// perform recursion if this is the case
if (typeof obj[key] === 'object' && !Array.isArray(obj[key]) && obj[key] !== null) {
let flat = flattenObject(obj[key])
Object.keys(flat).forEach((innerKey) => {
flattened[`${key} -> ${innerKey}`] = flat[innerKey]
})
}
else { // exit recursion here
flattened[key] = typeof(obj[key]) === 'string' ? obj[key] : JSON.stringify(obj[key])
}
})
return flattened
}
console.log(flattenObject(oldData))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment