I'm trying to find a more elegant way of converting a dictionary of dictionaries to an array of dictionaries and keeping the information of the keys of the original dictionary.
In the case of
let data= { boss: { name:"Peter", phone:"123"},
minion: { name:"Bob", phone:"456"},
slave: { name:"Pat", phone: "789"}
}
I want to come up with something that gives me
output = [ { role:"boss", name:"Peter", phone:"123"},
{ role:"minion", name:"Bob", phone:"456"},
{ role:"slave", name:"Pat", phone:"789"}
]
My solution goes by using the Object.keys method, but I think it's not very efficient. Something tells me I'm going the complex-all-around way and there must be an easier path, but I can't get it:
Object.keys(data)
.map((elem, i) => {
return Object.assign({role: e}, Object.values(data)[i]);
})
Is this the cleanest way to do what I intend to?
Thanks
You could map the entries and pick the key/role for a new object.
let data = { boss: { name: "Peter", phone: "123" }, minion: { name: "Bob", phone: "456" }, slave: { name: "Pat", phone: "789" } },
result = Object.entries(data).map(([role, values]) => ({ role, ...values }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With