0

I have a function that do something with an array of objects and i need to have just the name of property of another object to access it but i get undefined. It seems that i can't use a string to access to the object

function myFunction(arrayOfObjects, propName)
{
     for(var i = 0; i < arrayOfObjects.length; i++)
     {
         //This will give undefined, propName is simply a string coming from Object.keys()
         arrayOfObjects[i].propName = something;
     }

    return something;
}

Call to the function

var arrayOfNameProp = Object.keys(myObject);

var x = myFunction(arrayOfObjects, arrayOfNameProp[0]);
Matteo Bruni
  • 83
  • 2
  • 10

1 Answers1

2

As you pass it as a string, use bracket notation [propName] instead of dot notation .propName

arrayOfObjects[i][propName] = something;
Asons
  • 84,923
  • 12
  • 110
  • 165