danielr
danielr

Reputation: 130

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

Upvotes: 2

Views: 2147

Answers (2)

amrender singh
amrender singh

Reputation: 8239

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

Upvotes: 3

Mohammad Usman
Mohammad Usman

Reputation: 39322

You can use Map() to get the desired output:

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

let reducer = arr => {
    let map = new Map();

    arr.forEach(({key:k, value:v}) => {
        let values = map.get(k) || [];
        values.push(v);
        map.set(k, values);
    });

    return [...map.entries()].map(([k, v]) => ({key: k, values: v}));
};

console.log(reducer(data));

Upvotes: 0

Related Questions