0

I have a function that converts an object literal response data into an array:

From: [{"_id":"1","rating":7},{"_id":"2","rating":3}]

To: [7,3]

function createArray(fieldVar, responseData) {
   var newArray = responseData.map(function(data) { 
      return data.fieldVar // fails here because I am trying to use the fieldVar variable
   });
   return newArray
};

I call the function like this:

createArray('rating',response.rating_x)

This fails because of the data.fieldVar If I hardcode the call to data.rating it works correctly.

How do I pass in the 'rating' or any other name on the function call?

GavinBelson
  • 2,514
  • 25
  • 36
  • This is not the same as the question marked as duplicate.. I am trying to get the object.property notation inside of a function inside of another function – GavinBelson Feb 12 '17 at 20:00

1 Answers1

0

Try it with brackets

function createArray(fieldVar, responseData) {
   var newArray = responseData.map(function(data) { 
      return data[fieldVar] // access with brackets
   });
   return newArray
};

When using the dot-notation, the property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), not starting with a number. When you're using variables, you need to use bracket notation, else data.fieldVar would point to the property 'fieldVar' which probably doesn't exist. This is because the variable that you intended to access is not evaluated, but instead treated as a normal "string".

More informations on MDN: Property accessors

John
  • 131
  • 4