6
I’m trying to create a function map
, whose array and property to be returned are dynamic, that is, can be passed as a function parameter. Let’s take the array below as a use case.
const students = [
{ name: 'Anna', grade: 6 },
{ name: 'John', grade: 4 },
{ name: 'Maria', grade: 9 }
];
My first attempt was to make only the array dynamic, through a closure. I arrived at this result, which worked:
let teste = array => array.map(({ name }) => name);
In this case, I can pass any array that has the property name
that she will be returned.
Now, I need the property to also be dynamic and can be called from the function parameter. Something like this: getProperties(students, 'name')
.
I made the following code, but it didn’t work:
const getProperties = (array, prop) => array.map(({ prop }) => prop);
The return was [ undefined, undefined, undefined ]
.
Can help me solve this problem of how to make the property dynamic too?
Just an addendum, you could declare as
function getProperties(array, prop) { return array.map(etc...); }
- there is no advantage in using Arrow Function in this case (and in my opinion, the code is even a little more difficult to read, and without any gain in fact): https://stackoverflow.com/q/34361379 | https://stackoverflow.com/a/33040926– hkotsubo