save data to an object Using FOR

0

I have this for, the idea is to save the data in the object:

 let data_array = {};
        for (var i = 0; i < data.length; i++) {
          //console.log("datos completos ->  " +  data[i].id_expediente);
          data_array = {
                    'id_expediente':data[i].id_expediente,
                    'demandado':data[i].demandado,
                    'direccion':data[i].direccion,
                    'status':"",
                    'fecha_asignada':data[i].fecha_asig,
                    'tipo_juicio':data[i].tipo_juicio,
                    'lat':"",
                    'lng':""
                };

        }

and when printing with

console.log("data->" + JSON.stringify(data_array));

just save the last data.

{
"id_expediente": "3",
"demandado": "JORGE AVILA BERRIO",
"direccion": "Barlovento 1",
"status": "",
"fecha_asignada": "2018-05-01 00:00:00",
"tipo_juicio": "1",
"lng": ""
}

What is wrong with the For ?, the intention is to generate this format with the data of the For

{
"expedientes": [
{
  "id_expediente": "1",
  "demandado": "JORGE AVILA BERRIO",
  "direccion": "Barlovento 1",
  "status": "",
  "fecha_asignada": "2018-05-01 00:00:00",
  "tipo_juicio": "1",
  "lng": ""
},
{
  "id_expediente": "2",
  "demandado": "JORGE AVILA BERRIO",
  "direccion": "Barlovento 1",
  "status": "",
  "fecha_asignada": "2018",
  "tipo_juicio": "1",
  "lng": ""
},
{
  "id_expediente": "3",
  "demandado": "JORGE AVILA BERRIO",
  "direccion": "Barlovento 1",
  "status": "",
  "fecha_asignada": "2018",
  "tipo_juicio": "1",
  "lng": ""
}
]
}
    
asked by Eze 28.06.2018 в 19:33
source

2 answers

1

This is because you are constantly overwriting data_array .

Ideally, do it as follows:

data_array.push(data[i]);
    
answered by 28.06.2018 / 19:36
source
0

Changing the let by a var, and doing push of the items to the array.

  var data_array = {};
        for (var i = 0; i < data.length; i++) {
          //console.log("datos completos ->  " +  data[i].id_expediente);
          data_array.push({
                    'id_expediente':data[i].id_expediente,
                    'demandado':data[i].demandado,
                    'direccion':data[i].direccion,
                    'status':"",
                    'fecha_asignada':data[i].fecha_asig,
                    'tipo_juicio':data[i].tipo_juicio,
                    'lat':"",
                    'lng':""
                });
        }
    
answered by 28.06.2018 в 19:39