convert array to certain format

2

I have 2 arrays in javascript that you need to convert to a specific format, the current format of those 2 arrays is:

"diavalor": [
            "15",
            "27",
            "44",
            "63",
            "-1",
            "8",
            "9",
            "22"
        ],
        "diafecha": [
            "2018-08-30",
            "2018-08-30",
            "2018-08-30",
            "2018-08-30",
            "2018-08-30",
            "2018-08-30",
            "2018-08-30",
            "2018-08-30"
        ]

and the format I need is:

var data = [
            [1, 20],
            [2, 40],
            [3, 25],
            [4, 45],
            [5, 25],
            [6, 50],
            [7, 35],
            [8, 60],
            [9, 30]
          ];

and I do not know how to get to said format, I hope you can help me

update my problem is in the format because what I do:

var array=respuesta.humedad.diavalor;
        for (i = 0; i < array.length; i++) {
           data[i]=[[it,parseInt(array[i])]];
          it+=1;
        }
        console.log(data);
        console.log(data2);

gives a different format:

    
asked by zhet 31.08.2018 в 04:07
source

2 answers

1

Try something like this.

var valores = {
  "diavalor": [
    "15",
    "27",
    "44",
    "63",
    "-1",
    "8",
    "9",
    "22"
  ],
  "diafecha": [
    "2018-08-30",
    "2018-08-30",
    "2018-08-30",
    "2018-08-30",
    "2018-08-30",
    "2018-08-30",
    "2018-08-30",
    "2018-08-30"
  ]
};

var listaFinal = [];

var dias = valores.diavalor;
var fechas = valores.diafecha;

for (let i = 0; i < dias.length; i++) {
  const elemento = [ dias[i], fechas[i] ];
  listaFinal.push(elemento);      
}

console.log(listaFinal);

This is the result in console

    
answered by 31.08.2018 / 04:46
source
0

This is a pretty short way using .map() . By the way, you can cast the integer strings of the first array by adding + if you want.

var obj = {"diavalor": ["15","27","44","63","-1","8","9","22"],
"diafecha": ["2018-08-30","2018-08-30","2018-08-30","2018-08-30","2018-08-30","2018-08-30","2018-08-30","2018-08-30"]}


var arr = obj.diavalor.map((e,i)=>[+e,obj.diafecha[i]])

console.log(arr)

This is assuming that the relationship between the two arrays is in the order of them, and not in something external. In that case, the implementation would obviously be different.

    
answered by 31.08.2018 в 14:55