1
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
  • phrases.like[1].word if the arrays are always going to be static. Otherwise you'd have to iterate it and do some checking. Commented Oct 1, 2017 at 2:10
  • 1
    phrases is not an array, it is a JavaScript object. Commented Oct 1, 2017 at 2:12

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Got confused for a second. If my phrases keyword was a string, let say it was "like you" instead of "like". How would that work considering that there's a space in the string?
If there are spaces in the property name, you would have to use bracket notation, with quotes.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.