0

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?

3
  • What is the language? Commented Sep 26, 2021 at 4:30
  • 1
    The language is javascript thank you. Commented Sep 26, 2021 at 5:26
  • Just use the bracket notation consequently ... [object[array[1]] Commented May 22, 2024 at 12:04

1 Answer 1

1

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]]);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.