ggonmar
ggonmar

Reputation: 839

Convert a dictionary into an array keeping the dictionary keys

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

Upvotes: 4

Views: 5816

Answers (3)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

You can use Array.prototype.reduce and Object.entries to loop over every entry in the dictionary and reduce it to an array:

const data = { boss: { name: "Peter", phone: "123" }, minion: { name: "Bob", phone: "456" }, slave: { name: "Pat", phone: "789" } };

function getArray(data) {
  return Object.entries(data).reduce((a, [k, v]) => {
    a.push({role: k, ...v});
    return a;
  }, []);
}
console.log(getArray(data));

Upvotes: 0

Derek Wang
Derek Wang

Reputation: 10204

Using Object.entries, you can get [key, value] pairs as array and can get teh result you want using Array.map function.

let data = {
  boss: { name:"Peter", phone:"123"},
  minion: { name:"Bob", phone:"456"},
  slave: { name:"Pat", phone: "789"}
};

const result = Object.entries(data).map(([key, value]) => ({
  role: key,
  ...value
}));
console.log(result);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386868

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; }

Upvotes: 7

Related Questions