将具有重复键的键值数组转换为具有唯一键和value数组属性的对象数组 [英] Convert a key-value array with duplicate keys into array of object with unique key, and value array property
问题描述
我有一组键/值对。这些键有时是重复的,并且每个键的值始终是唯一的。
我想将每个唯一键压缩为一个对象,以便我拥有一个键和一组关联值作为属性。
是否有方便的javascript函数来执行此操作?
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?
此
pairArray = [
{ key: "a", value: "1" },
{ key: "a", value: "2" },
{ key: "b", value: "1" },
{ key: "b", value: "2" },
];
成为
objectArray = [
{ key: "a", values: ["1", "2"] },
{ key: "(", values: ["1", "2"] }
];
推荐答案
您可以简单地使用 Array.reduce()
将对象的 key
属性作为地图的键来创建地图,在该地图上的 Object.values()
将为您提供所需的结果:
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);
这篇关于将具有重复键的键值数组转换为具有唯一键和value数组属性的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!