He estado tratando de convertir estos datos:
var myArray = [ [1,2,3,4], ["1","2","3","4"], ["a", "b", "c", "d"] ]a esto:
var result = [ { "num": 1, "str": "1", "let": "a" }, { "num": 2, "str": "2", "let": "b" }, { "num": 3, "str": "3", "let": "c" }, { "num": 4, "str": "4", "let": "d" } ]Cualquier ayuda será extremadamente útil. He intentado varias iteraciones pero ninguna de ellas produce lo que espero.
Estoy tratando de usar esto:
objectified_data = array_data.map(function(x) { return { "num": x[0], "str": x[1], "let": x[2] } })Pero no puedo entender cómo hacer que el conjunto homogéneo de matriz sea heterogéneo para que esto funcione. En última instancia, estoy tratando de filtrar ciertas claves, por lo que los datos originales no funcionan para esa tarea.
Puede lograr esto con un simple para
var myArray = [ [1, 2, 3, 4], ["1", "2", "3", "4"], ["a", "b", "c", "d"] ] const json = []; for (let i = 0; i < myArray[0].length; i++) { json.push({ num: myArray[0][i], let: myArray[1][i], str: myArray[2][i], }); } console.log(json);Prueba esto
var myArray = [[1,2,3,4],["1","2","3","4"],["a", "b", "c", "d"]]; let result = myArray[0].map((v, i) => ({ "num": myArray[0][i], "let": myArray[1][i], "str": myArray[2][i] })) console.log(result)Solo una solución básica. ¿Te gustaría i fuera dinámico, creo? En ese caso, puede verificar el tamaño de la primera matriz anidada y usarla como i .
let x = 0; let y = 1; let z = 2; let json = []; for(let i=0; i<4;i++){ let item = {}; item = { ["num"]: myArray[x][i], ["let"]: myArray[y][i], ["str"]: myArray[z][i] } result.push(item); }