Reputation: 1348
How would you implement a mapping function, from an object keys to another object that has a property with that specific key, preserving the object structure
For example, given this input object:
{
person: {
first_name: "fn",
last_name: "ln",
address: {
city: "c",
street: "s",
},
movies: [
{
title: "movie1"
},
{
title: "movie2"
}
]
}
}
the result should be:
{
name: "person",
children: [
{
name: "first_name"
},
{
name: "last_name"
},
{
name: "address",
children: [
{
name: "city"
},
{
name: "street"
}
]
},
{
name: "movies",
children: [
{
name: "title"
}
]
}
]
}
I've tried with some recursive object traversals but the implementation was really ugly. I feel that there is an easier way to handle it
Upvotes: 1
Views: 55
Reputation: 36594
You can do that using recursion. Create a function which takes an entry as input. Entry is an array of two element which contains key value pair for an object. [key,value]
const obj = { person: { first_name: "fn", last_name: "ln", address: { city: "c", street: "s", }, movies: [ { title: "movie1" }, { title: "movie2" } ] } }
function getKeys(entry){
let obj = {
name:entry[0],
children:[]
}
const { children } = obj
let val = entry[1]
for(let k in val){
if(Array.isArray(val[k])){
children.push(getKeys([k,val[k][1]]));
}
else if(typeof val[k] === "object"){
children.push(getKeys([k,val[k]]))
}
else children.push({name:k})
}
if(!obj.children.length) delete obj.children;
return obj
}
console.log(getKeys(Object.entries(obj)[0]))
Upvotes: 1