I have an array of objects
"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] }
Now keep in mind that the keys are dynamic. In this instance it's width and height.
I do actually have solution.
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;
But can I make this shorter?