Created
October 19, 2022 21:20
-
-
Save damiancipolat/787c9f694a44946e5800ab61b2f1f5d5 to your computer and use it in GitHub Desktop.
Flat a JS object
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
// Receive an | |
const flatArray = (key,list)=>{ | |
let obj={}; | |
list.forEach((item,i)=>{ | |
obj[`${key}.${i}`]=item; | |
}); | |
return obj; | |
} | |
// Declare a flatten function that takes | |
// object as parameter and returns the | |
// flatten object | |
const flattenObj = (ob) => { | |
// The object which contains the | |
// final result | |
let result = {}; | |
// loop through the object "ob" | |
for (const i in ob) { | |
// We check the type of the i using | |
// typeof() function and recursively | |
// call the function again | |
if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) { | |
const temp = flattenObj(ob[i]); | |
for (const j in temp) { | |
// Store temp in result | |
result[i + '.' + j] = temp[j]; | |
} | |
} | |
// Else store ob[i] in result directly | |
else { | |
if (Array.isArray(ob[i])&&ob[i].length>0){ | |
const flatList = flatArray(i,ob[i]); | |
result={ | |
...result, | |
...flatList | |
}; | |
} | |
else | |
result[i] = ob[i]; | |
} | |
} | |
return result; | |
}; | |
let obj = { | |
Company: "GeeksforGeeks", | |
Address: "Noida", | |
pepe:[1,2,3,4], | |
contact: +91 - 999999999, | |
mentor: { | |
HTML: "GFG", | |
CSS: "GFG", | |
JavaScript: "GFG" | |
}, | |
books:{ | |
colors:['red','green'] | |
} | |
}; | |
console.log(obj); | |
console.log(flattenObj(obj)) | |
console.log(flatArray('tmp',[1,2,3,4])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment