Last active
January 31, 2021 14:03
-
-
Save naveenrawat51/26d5edc60d8e96cdd06a2487672ec5d6 to your computer and use it in GitHub Desktop.
flatten_nested_object in 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
let flattenObj = function(inputObject) { | |
let flattenedObj = {}; | |
for (let obj in inputObject) { | |
if (inputObject[obj].constructor === Object) { | |
let flatObj = flattenObj(inputObject[obj]); | |
for(let i in flatObj) { | |
flattenedObj[i] = flatObj[i]; | |
} | |
} else { | |
flattenedObj[obj] = inputObject[obj] | |
} | |
} | |
return flattenedObj; | |
} | |
let obj = { | |
name: 'Sonit', | |
address: { | |
phone: '123123123', | |
contact: { | |
email: 'sonit.bhaker@gmail.com' | |
}, | |
age: { | |
a: { | |
b: { | |
c: { | |
d: { | |
e: { | |
val: 3 | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
}; | |
console.log(flattenObj(obj)); | |
// flatten nested array | |
let flattenArr = function(inputArr) { | |
console.log('inputArr: ', inputArr); | |
let flattenedArr = []; | |
for(let arr of inputArr) { | |
if (arr.constructor === Array) { | |
let flatArr = flattenArr(arr); | |
for(let i of flatArr) { | |
flattenedArr.push(i) | |
} | |
} else { | |
flattenedArr.push(arr) | |
} | |
} | |
return flattenedArr; | |
} | |
const arr = [1,[2,3,[4,5,[6,78,[11], 12], 22, 11], 1], 12, 11, 1234, [22,[33,[44]]]]; | |
console.log(flattenArr(arr)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment