0

I have a for loop that adds properties to the data object

words is an array of strings

for (let i = 0; i < words.length; i++) {
  let word = words[i];
  data[word] = i;
}

After that, my objext looks like this:

data = {"the": 0, "of": 1, "and": 2, "to": 3, "a": 4, …};

I have tried

data['the'];

but it returns undefined

How do I retrieve the value of the property?

Here is my full code

let vocab = {};

$.ajax({
  url: "10000words.txt",
  success: function(data) {
    data = data.split(/\n/).slice(0, 10000);
    for (let i = 0; i < data.length; i++) {
      let word = data[i];
      vocab[word] = i;
    }
    console.log(vocab['test']);
  }
});

When I type vocab into the console, it prints out vocab but when I try vocab['the'] it returns undefined

17
  • 4
    data['the'] works fine. You're doing something else wrong. Please provide an stackoverflow.com/help/mcve Commented Jul 19, 2018 at 23:33
  • 1
    Are you trying to access vocab outside the ajax function? Commented Jul 19, 2018 at 23:42
  • 1
    @bena The question was whether you’re trying to access vocab outside the success callback, not whether you’ve declared it outside. Your issue is impossible to reproduce, if you didn’t actually access vocab outside of success. That’s why I think the most likely issue is this: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference Commented Jul 19, 2018 at 23:45
  • 1
    @bena Actually… try console.log([...Object.keys(vocab).find((word) => /t[^a-z]*h[^a-z]*e/.test(word))]); and see whether it matches ["t", "h", "e"]. There may be invisible characters within your words, thus vocab.the won’t work. Commented Jul 20, 2018 at 0:17
  • 1
    Your words probably have trailing spaces. Commented Jul 20, 2018 at 1:18

1 Answer 1

1

Here is an example of how to get a value by the object key.

const words = ['Hello', 'world'];
const data = {};

for(let i = 0; i < words.length; i++) {
  const word = words[i];
  data[word] = i;
}

const index = data['Hello'];

document.write(index);

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.