4

So I basically import a JSON file. I get back many arrays and each array has 4 elements in it. I want to parse the 3rd element from each array into it's own variable array.

$("#nextQ").click(function() {

  var Quotes = [];
  var totalQ //The total number of available quotes to choose from

  //Get quotes from JSON file
  $.ajax({
    url: '../facts.json',
    datatype: 'json',
    type: 'get',
    success: function(data) {
      console.log(data[0][2]); //This WORKS
      console.log(data.length); //Returns 64

      totalQ = data.length;

      for (i = 0; i <= totalQ; i++) {
        Quotes[i] = data[3][2]; //This WORKS
        Quotes[i] = data[i][2]; //This gives ERROR

      }
    }
  });

});

When I use data[i][2] I get this error: Uncaught TypeError: Cannot read property '2' of undefined. However this error doesn't occur if I use data[6][2] or any other number.

5
  • 1
    i <= totalQ; to i <totalQ; Commented Mar 5, 2016 at 5:39
  • Thanks, any idea why that would give me an error on the 2nd index and not the 64th? Commented Mar 5, 2016 at 5:39
  • 1
    Or more jQuery'ish -> $.each(data, function() {... Commented Mar 5, 2016 at 5:40
  • 1
    @Badrush - the first index in an array is zero, yet length really starts at one, as the length would be 1 if the array had one item, but that item would be at array[0]. When you loop, you loop to array.length - 1, but you're looping until i is the same as the length, so you're trying to look up array[length], which doesn't exists Commented Mar 5, 2016 at 5:42
  • 1
    @Badrush , data[data.length] will be undefined, you are trying to get the property of undefined. The property you are trying to access is 2 which is undefinded. Commented Mar 5, 2016 at 5:51

1 Answer 1

3

You need to update the for loop condition from i <= totalQ; to i <totalQ; , since index starts from 0

for (i = 0; i < totalQ; i++) {
    Quotes[i] = data[i][2]; 
}

Or you can use $.each() as @adeneo suggested

$.each(data,function(i,v){
  Quotes[i] = v[2]; 
})

Or you can use native javascript map()

Quotes = data.map(function(v){
  return v[2]; 
}) 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks man, this worked. I would have caught this if the error hadn't told me the issue was with the 2nd index (random???)
@Badrush , data[data.length] will be undefined, you are trying to get the property of undefined

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.