Search code examples
javascriptarraysobjectkey-value

Convert a key-value array with duplicate keys into array of object with unique key, and value array property


I have an array of key/value pairs. The keys are sometimes duplicated, and the values are always unique per key. I want to condense each unique key to an object, so that I have a key and an array of the associated values as a property. Are there any handy javascript functions to do this?

This

pairArray = [
{ key: "a", value: "1" },
{ key: "a", value: "2" },
{ key: "b", value: "1" },
{ key: "b", value: "2" },
];

Becomes

objectArray = [
{ key: "a", values: ["1", "2"] },
{ key: "(", values: ["1", "2"] }
];

Solution

  • You can simply create a map using Array.reduce() with your key property of your object as key of your map, Object.values() on that map will give you the desired result :

    Assuming you have a typo in your expected output. You can try the following :

    const pairArray =  [ { key: "a", value: "1" }, { key: "a", value: "2" }, { key: "b", value: "1" }, { key: "b", value: "2" }, ];
    
    const result = Object.values(pairArray.reduce((acc, {key, value})=>{
      acc[key] = acc[key] || {key, values : []};
      acc[key].values.push(value);
      return acc;
    },{}));
    
    console.log(result);