I have an object that looks like this:
{ role1: ["id1", "id2", "id3"], role2: ["id1", "id2"], role3: ["id2", "id4"] }
I would like to transform this into an array of objects, making the ids the unique identifiers and the roles into arrays, like so:
[
{ id: "id1", roles: ["role1", "role2"] },
{ id: "id2", roles: ["role1", "role2", "role3"] },
{ id: "id3", roles: ["role1"] },
{ id: "id4", roles: ["role3"] },
]
This is how I do it right now, but I'm not sure if there's a better way. It feels like I'm overcomplicating things.
const obj = {
role1: ["id1", "id2", "id3"],
role2: ["id1", "id2"],
role3: ["id2", "id4"]
};
const users = [];
Object.entries(obj).forEach(([key, ids]) => {
ids.forEach(id => {
const user = users.find(x => x.id === id);
if (user) {
user.roles.push(key);
return;
}
users.push({
id,
roles: [key]
});
});
});
console.log(users);