0

I have the following object array in which I'm storing bus route by number and then by name:

var routearray =[
ruta01 = 
    {
        via01: "Progress",
        via02: "Ten",
        via03: "S",
        via04: "Maria"
    },
ruta02 =
    {
        via01: "Exterior",
        via02: "Interior"
    },
ruta03 =
    {
        via01: "University",
        via02: "Henry St"
    },];

And I have the following code with which I want to access the value of each property:

for(i=0;i<routearray.length;i++) //iterates through the array's objects
    {
        var props = Object.keys(routearray[i]); //array that stores the object properties
        for(j=0;j<props.length;j++) //iterates through specific object properties
        {
            console.log(props[j]); //shows the property names
            var propertystring = String(props[j]); //transforms the property name into string
            console.log(routearray[i].propertystring]; //should access the property value
        }

    }

When the last line of the code executes, I get 8 "undefined" results in the console. If I change it to something like:

console.log(routearray[i].via01];

It works just fine, but I'm not sure why it is not accessing the value if the string is supposed to work correctly. What am I doing wrong? Is there a better way?

Abraham L
  • 346
  • 2
  • 12
  • You don't need to convert the property names of the array element to strings; they're already strings. And you're looking for the `[ ]` operator: put the name of the variable containing the property name in the brackets, just like you put `i` in the brackets to do array indexing. It's exactly the same thing. – Pointy Apr 27 '16 at 20:41
  • I thought about it but sometimes one tends to think the complex way. Thank you. – Abraham L Apr 28 '16 at 13:17

1 Answers1

1

It should be:

console.log(routearray[i][propertystring]);

In general, when you do "someObject.key" then the actual value "key" must exist as a property in "someObject". But, if you do "someObject[key]", then the value contained inside the variable "key" must exist as a property in "someObject".

Alexandru Godri
  • 528
  • 3
  • 7
  • Great! Thanks, much appreciated, was kinda obvious but sometimes we try to search for the most complex solution. – Abraham L Apr 28 '16 at 13:18