Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

242
Vistas
What would the loop look like to modify an array like this?

Is there a way in javascript to iterate through every value of a specific key from an object that is part of an array of objects and then create a new item for each value using a different key? Please allow me to explain with code what I would like to accomplish here.

This is what I have:

const x = [{
  name: 'name1',
  value: ['value1', 'value2', 'value3']
}, {
  name: 'name2',
  value: ['value4', 'value5', 'value6']
}]

This should be the new result:

const y = [{
  'name1': 'value1',
  'name2': 'value4',
}, {
  'name1': 'value2',
  'name2': 'value5',
}, {
  'name1': 'value3',
  'name2': 'value6',
}]

Any help will be truly appreciated!

Here is what I've tried so far. (It works, but I'm pretty sure there is a simpler way).

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);
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I believe this should work:

//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 
    })
})

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda