I have this object:
const sampleObj = {
home: true,
products_edit: true,
products_create: true,
orders_delete: true,
pages_category_create: true
}
I want to convert the above object to:
const result = {
home: {
status: 'full'
},
products: {
status: 'limited',
subOptions: {
edit: true,
create: true
}
},
orders: {
status: 'limited',
subOptions: {
delete: true,
}
},
pages: {
status: 'limited',
subOptions: {
category: {
status: 'limited',
subOptions: {
create: true,
}
},
}
}
}
So I want to convert the object keys to nested objects based on _ character and the _ parts could be more than 3.
If the key is one part like "Home" the status should be "full", otherwise it should be "limited".
This is my current code:
function rolesFlattener(obj) {
let final = {};
Object.keys(obj).forEach((item, index) => {
const path = item.split('_');
if(path.length > 1) {
path.reduce((prev, current, i, array) => {
if(!final[prev]) {
final[prev] = {
status: 'limited',
subOptions: {}
}
}
final[prev].subOptions[current] = true;
return current;
});
}
else {
final[path[0]] = {
status: 'full'
}
}
})
console.log(final)
}
// userRole: {
// home: {
// status: 'full'
// },
// products: {
// status: 'limited',
// subOptions: {
// edit: true,
// create: true
// }
// },
// orders: {
// status: 'limited',
// subOptions: {
// delete: true,
// }
// },
// pages: {
// status: 'limited',
// subOptions: {
// category: {
// status: 'limited',
// subOptions: {
// create: true,
// }
// },
// }
// }
// }
let sampleObj = {
home: true,
products_edit: true,
products_create: true,
orders_delete: true,
pages_category_create: true
}
rolesFlattener(sampleObj)