Wrong stored and displayed information

Asked

Viewed 30 times

0

Hello, I have the following code:

    var marcas = {
        nome: '',
        fipeId: ''    
    };

    var marcasVet = [];
    var select;


$.ajax({
    dataType: "json",
    url: 'http://fipeapi.wipsites.com.br/carros/marcas',

    success: function(data) {

        for (var i = 0; i < data.length; i++) {

            marcas.nome = data[i].name;
            marcas.fipeId = data[i].id;            


            marcasVet[i] = marcas;

            select += '<p> Marca: ' + marcasVet[i].nome + ' Marca id (Fipe): ' + marcasVet[i].fipeId + '</p>';

        }

        $('#info').html(select);
    }

});

The data is stored in the vector marcasVet[] and shown inside a div with id="info"

The problem is that when asking to show the information of marcas.fipeId it just shows the value 120, in any vector position marcasVet[].

Changing the code $('#info').html(select); for $('#info').html(marcasVet[10].fipeId); or any other position (1,2,3,4...87) it shows only the value 120.

I’d like you to show the value it shows when it changes to var select.

Does anyone know where the mistake is?

Thank you

1 answer

0


Reset the variable value again marcas within the for. And use the method push() to add the object in its vector marcasVet. Behold:

    
var marcas = {nome: '', fipeId: ''};
var marcasVet = [];

for (var i = 0; i < 5; i++) {
 
  marcas = {nome: '', fipeId: ''};
  
  marcas.nome = "Nome "+i;
  marcas.fipeId = "Fipe "+i;
  
  marcasVet.push(marcas);
}

console.log(marcasVet);

  • would you be able to tell me why I need to reset the value of the tags variable again, and I will change its value with each increment? I’m having another problem only now with 2 loops where there is an array that each Dice should receive a new array. But, when placing the array inside the other one it prints right but when it finishes it says it is Undefined

Browser other questions tagged

You are not signed in. Login or sign up in order to post.