const userProfile = {
id: 1,
name: {
first: "John",
last: "Doe"
},
age: 30,
address: {
street: "123 Main St",
city: "Springfield",
state: "IL",
zip: "62704",
country: "USA"
},
contacts: {
email: "john.doe@example.com",
phone: {
home: "555-1234",
work: "555-5678",
mobile: "555-8765"
}
},
preferences: {
notifications: {
email: true,
sms: false,
push: true
},
theme: "dark",
language: "en-US"
},
friends: [
{
id: 2,
name: "Jane Smith",
email: "jane.smith@example.com"
},
{
id: 3,
name: "Mike Johnson",
email: "mike.johnson@example.com"
}
],
active: true,
createdAt: "2020-01-01T12:00:00Z"
};
const obj = {a:1, b:{c:{d:3,e:[4,5,6]}}}
const flattenObj = (obj, objKey="") => {
let flat = {}
for(const [key, value] of Object.entries(obj) ){
if(typeof value === "object" && !Array.isArray(value)){
flat = { ...flat ,...flattenObj(value, objKey?objKey+"."+key:key)}
}else{
flat[`${objKey?objKey+"."+key:key}`]=value
}
}
return flat
}
console.log(flattenObj(userProfile))
To embed this project on your website, copy the following code and paste it into your website's HTML: