1

I have the following function which takes a dataset, field name and search string then uses ES2015's arrow functions to find the result.

Example call is:

var whatever = myDataSet.find(entry => entry.name === 'John');

I need to build this from arguments within a function but I cannot get the field name in.

The function:

findSingle: function(dataSet, fieldName, searchString){
    return dataSet.find(entry => entry.fieldName === searchString);
}

Which I'd call with:

my.nameSpace.findSingle(dataSetName, 'name', 'John');

And I expect it to then call:

dataSetName.find(entry => entry.name=== 'john');

But it fails. (If I hard code entry.name it work as expected) I'm pretty sure it's because I'm passing a string to be an object property for entry.name but I can't think of another way to do this.

Is it possible to pass strings into object properties like this or should I do it a different way?

StudioTime
  • 22,603
  • 38
  • 120
  • 207

1 Answers1

5
findSingle: function(dataSet, fieldName, searchString){
    return dataSet.find(entry => entry[fieldName] === searchString);
}

To be able to use a variable to fetch an object property, you have to use the bracket notation (object[key]). Dot notation (object.key) is interpreted literally and looks for a key named "key".

In your case entry.fieldName equals entry['fieldName']. To use the variable called fieldName, you have to do entry[fieldName].

marton
  • 1,300
  • 8
  • 16