flat-obj-keys
by saidulu401
JavaScript
/*Code START*/
const data = {
id: 1,
user: {
name: "Bob",
roles: ["admin", "editor"],
contact: {
email: "[email protected]",
phones: [
{ type: "home", number: "123-456" },
{ type: "work", number: "987-654" }
]
}
},
active: false
};
/*Code END*/
// solution
const flattenObj = (inputObj) => {
// logic to convert inputObj
let result = {};
const flat = (input,key='')=> {
if(typeof input !== 'object'){
result[key]= input;
} else {
//let k= '';
for(let i in input){
const k = key?`${key}.${i}`:i;
//key= `${key}.${i}`;
flat(input[i],k);
// if(typeof input[i] !== 'object'){
// result[k]= input[i];
// } else {
// key= `${key}.${i}`;
// flat(input[i],key);
// }
}
}
//return result;
}
flat(inputObj);
/* for(let i in inputObj){
if(typeof inputObj[i] !== 'object'){
result[i]= inputObj[i];
} else {
const newKey = i;
flat(inputObj[i],newKey);
}
} */
return result;
}
console.log(flattenObj(data));
//console.log(typeof {})
//Expected Output:
/* {
"id": 1,
"user.name": "Bob",
"user.roles.0": "admin",
"user.roles.1": "editor",
"user.contact.email": "[email protected]",
"user.contact.phones.0.type": "home",
"user.contact.phones.0.number": "123-456",
"user.contact.phones.1.type": "work",
"user.contact.phones.1.number": "987-654",
"active": false
} */