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

。_饼干妹妹 提交于 2020-05-17 08:24:05

问题


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

回答1:


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 :

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

let result = Object.values(pairArray.reduce((acc, {key, value})=>{
  acc[key] = acc[key] || {key, values : []};
  acc[key].values.push(value);
  return acc;
},{}));

console.log(result);



回答2:


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


来源:https://stackoverflow.com/questions/54103990/convert-a-key-value-array-with-duplicate-keys-into-array-of-object-with-unique-k

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!