我有一个对象数组
"options": [
{
"width": 10,
"height": 20
},
{
"width": 20,
"height": 40
},
{
"width": 30,
"height": 60
}
]
That I want convert to the following
{ width: [10, 20, 30], height: [20, 40, 60] }
请记住,这些键是动态的。在此示例中,它们是width
和height
。
我确实有解决方案。
const pluck = (arr: Record<string, any> | undefined, property: string) => {
return arr?.map((obj: any) => {
return obj[property];
});
};
const unique = (arr: any[] | undefined) =>
arr ? Object.keys(Object.assign({}, ...arr)) : null;
const keys = unique(myArray);
const options = keys
? Object.fromEntries(keys.map((key) => [key, pluck(myArray, key)]))
: null;
但我能不能把这个变得更短?