-1

I’d like to know if it is possible to create a function that returns a field from an object given in parameter.

const data = {
  "name": "Doe",
  "firstName": "John",
  "age": 30,
  "from": "USA"
};

function returnField(field) {
  return data.field;
}
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
lolozen
  • 386
  • 1
  • 4
  • 19
  • 1
    https://stackoverflow.com/questions/2462800/how-do-i-create-a-dynamic-key-to-be-added-to-a-javascript-object-variable – bill.gates Jul 01 '20 at 13:54

1 Answers1

1

yes, its possible by using [] instead of .

data = {
 "name" : "doe",
 "firstname" : "jhon",
 "age" : 30,
 "from" : usa
 }

function returnField(field){
    return data[field]
}

In general you dont even need the function for it (unless you want to have more logic or some validation there) and just using data[field] directly.

libik
  • 22,239
  • 9
  • 44
  • 87