Javascript - How to access a word in this array of array of strings?

98 views Asked by At
var phrase1 = [];
phrase1.push({word: "I", x:50, y:50});
phrase1.push({word: "like", x:70, y:50});
phrase1.push({word: "you", x:120, y:50});

var phrase2 = [];
phrase2.push({word: "Well", x:50, y:50});
phrase2.push({word: "I", x:110, y:50});
phrase2.push({word: "tried", x:130, y:50});
phrase2.push({word: "to", x:190, y:50});

var phrase3 = [];
phrase3.push({word: "Hey", x:40, y:50});
phrase3.push({word: "where", x:100, y:50});
phrase3.push({word: "you", x:180, y:50});
phrase3.push({word: "at", x:220, y:50});

var phrases = {"like" : phrase1,
             "tried" : phrase2,
             "where" : phrase3
             };

This is a snippet of the code I received. I'm having trouble figuring out how to access a word from the phrases array. Let's say I want to access the word "like" from phrase1, through phrases, what is the correct syntax to do so?

Tried so many combinations that I'm just stumped now. If someone could point me to the right direction, that would be great. Thank you!

I can access individual phrases with

phrase1[1].word

But unable to find a way to get it through phrases.

2

There are 2 answers

2
user2182349 On

phrases isn't an array, it is an object.

You can access the properties using dot notation, like this:

phrases.like[0].word

You can also use bracket notation, as follows:

phrases["like"][0].word
0
JMP On

To access phrases as an array, it needs to be an array (you have it as an object):

phrases=[phrase1, phrase2, phrase3];

Then:

phrases[0][1].word;

works.