2

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"] }
];
2
  • 3
    So, what you tried? Commented Jan 9, 2019 at 5:54
  • Edit your question and show us what you tried. Commented Jan 9, 2019 at 6:02

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Deleted my answer because is identical to your answer.. Although it has not been copied ;)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.