Search code examples
javascriptarraysobject

Acessing an object properyt with array bracket notation


I want to access a specific property in an object. Using an array for example

let array = ["tom","tony", "jerry"];

let object = {
  tony: "Brother", 
  tom: "Uncle", 
  jerry: "Cousin", 
};

object.array[1];

I'm trying to access object.tony but what happens is that it returns object."tony" instead.

The problem is that it returns it as a string so it causes an error.

Is it possible to return array[1] not as a string?


Solution

  • In object.array[1], JS will think your looking for array inside object, which does not exist. If an array was in the object, it would work:

    let object = {
        array: ["tom", "tony", "jerry"],
        // some other stuff...
    };
    console.log(object.array[1]);

    You can use brackets instead:

    object[array[1]];
    

    Example:

    let array = ["tom","tony", "jerry"];
    let object = { tony: "Brother", tom: "Uncle", jerry: "Cousin", };
    console.log(object[array[1]]);