¿Hay alguna forma en javascript de iterar a través de cada valor de una clave específica de un objeto que forma parte de una matriz de objetos y luego crear un nuevo elemento para cada valor usando una clave diferente? Permítanme explicar con código lo que me gustaría lograr aquí.
Esto es lo que tengo:
const x = [{ name: 'name1', value: ['value1', 'value2', 'value3'] }, { name: 'name2', value: ['value4', 'value5', 'value6'] }]Este debería ser el nuevo resultado:
const y = [{ 'name1': 'value1', 'name2': 'value4', }, { 'name1': 'value2', 'name2': 'value5', }, { 'name1': 'value3', 'name2': 'value6', }]¡Cualquier ayuda será realmente apreciada!
Esto es lo que he intentado hasta ahora. (Funciona, pero estoy bastante seguro de que hay una forma más sencilla).
const y = []; const z = []; const xLength = x.length for (let i = 0; i < xLength; i++) { x[i].value.forEach((item, index) => { z[index] = z[index] || []; z[index].push(x[i].name, item); }); } z.forEach((items, index) => { const obj = {}; items.forEach((item, k) => { if (k % 2) { obj[items[k - 1]] = item; } else { obj[item] = null; } }); y.push(obj); });Creo que esto debería funcionar:
//start with array to store the answer let y = [] //Next iterate threw each object in your 'x' array passing in to the callback xObj which is each object in your x array x.forEach((xObj)=> { //store the name value just to make it easier to read let name = xObj.name //iterate through the values in each xObj, getting the 'value' and the index xObj.value.forEach((value, index)=>{ //check if the y array has anything at the same index, if not create a blank object if(!y[index]) y[index]= {} //put in that object a key:value with the 'name' and 'value' y[index][name] = value }) })