简体   繁体   中英

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"],
}
  • 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM