Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
Calling index of an array in loop causing error

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.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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]; 
}) 
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda