Created
February 10, 2020 04:50
-
-
Save cedrickvstheworld/0ec85dfeda2c403fc1f40f1fd0887829 to your computer and use it in GitHub Desktop.
flatten js object to Depth = 1
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
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