RH-st
RH-st

Reputation: 157

How can I pass a parameter to callback function which is inside map function

I am a new learner of JS, there is a function like this

const generateNum = (array, key) => {
    return array.map(i => parseFloat(i.key));
}

however, in this fn, key is declared but never used, how can I pass this parameter to the inside of map fn. Many thanks

Upvotes: 1

Views: 570

Answers (2)

Kostas
Kostas

Reputation: 1903

const generateNum = (array, key) => {
  return array.map(i => parseFloat(i[key]));
}

A simple example for explanation.

let person = {
  name: 'John',
  age: 30,
};

let key = 'name';

person.key; // does not exist (only name and age is inside person object) so it would be undefined
person[key]; // exists because it means person.name actually

Upvotes: 1

VpsOP
VpsOP

Reputation: 41

By doing i.key you are trying to access key property of the i object. Since you are passing key as a parameter to generateNum function you can use key as a variable inside the function body.

const generateNum = (array, key) => {
  return array.map(i => parseFloat(i[key]));
}

Upvotes: 4

Related Questions