Last active
November 9, 2018 02:41
-
-
Save tkdn/657895d830aaf0f55670b8bf11914b1a to your computer and use it in GitHub Desktop.
like `array_pluck` on Laravel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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