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?

1
  • 2
    entry[fieldName] Commented Jul 5, 2016 at 13:50

1 Answer 1

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].

Sign up to request clarification or add additional context in comments.

1 Comment

Damn it, tried everything but this - thanks! Will accept when I can

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.