Skip to content

Instantly share code, notes, and snippets.

@tkdn
Last active November 9, 2018 02:41
Show Gist options
  • Save tkdn/657895d830aaf0f55670b8bf11914b1a to your computer and use it in GitHub Desktop.
Save tkdn/657895d830aaf0f55670b8bf11914b1a to your computer and use it in GitHub Desktop.
like `array_pluck` on Laravel
const pluck = (
array: Array<{[key: any]: value: any}>,
props: string[],
pickedKey: string,
): {[valuePickedByKey: any]: {[prop:any]: any}} => {
return array.reduce((prevOut, item) => {
const valuePickedByKey = item[pickedKey];
const pickedObj = props.reduce((prevItem, pickProp) => {
return {
...prevItem,
[pickProp]: item[pickProp]
};
}, {});
return {
...prevOut,
[valuePickedByKey]: pickedObj,
}, {});
};
const arr = [
{ id: 1, fruit: "banana", color: "yellow", count: 4},
{ id: 2, fruit: "apple", color: "red", count, 0},
];
const plucked = pluck(arr, ["fruit", "color"], "id");
console.log(plucked);
// {
// 1: {fruit: "banana", color: "yellow"},
// 2: {fruit: "apple", color: "red"},
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment