ComCool
ComCool

Reputation: 1103

Convert key/value array

What is the best way to convert to following array. Do I need to map over it or is there some other way with Object.values etc:

[
  {
    key: "eyeColor",
    value: "Blue/Green",
   },
   {
     key: "eyeColor",
     value: "Blue",
   },
   {
     key: "hairColor",
     value: "black",
   }
];

into:

{
  hairColor: ["Blond", "Brown"],
  eyeColor: ["Blue"],
}

Upvotes: 0

Views: 64

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28434

  • Using Array#reduce, iterate over the array while updating a Map where the key is the key properties and the value is the corresponding grouped-value properties.
  • Using Array#map, iterate over the above pairs and convert to objects:

const data = [ { key: "eyeColor", value: "Blue/Green" }, { key: "eyeColor", value: "Blue" }, { key: "hairColor", value: "black" } ];

const groupedPairs = [...data.reduce((map, { key, value }) =>  map.set(key, [...(map.get(key) ?? []), value]), new Map)];

const list = groupedPairs.map(([ prop, list ]) => ({ [prop]: list }))

console.log(list);

EDIT AFTER CHANGE OF EXPECTED OUTPUT:

const data = [ { key: "eyeColor", value: "Blue/Green" }, { key: "eyeColor", value: "Blue" }, { key: "hairColor", value: "black" } ];

const res = data.reduce((acc, { key, value }) => ({
  ...acc, [key]: [...(acc[key] ?? []), value]
}), {});

console.log(res);

Upvotes: 1

Related Questions