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

275
Vistas
How to make an array of objects out of two non symmetrical arrays?

am stuck now for the whole day and cannot get any further. I know, that I am missing a small thing, but just can't find it.

I got two arrays:

arrKeys = ["a", "b", "c"]
arrValues = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]

I would like to get an array of objects, that looks like:

myObj = [
 {
  "a": 1,
  "b": 2,
  "c": 3
 },
 {
  "a": 4,
  "b": 5,
  "c": 6
 },
 {
  "a": 7,
  "b": 8,
  "c": 9
 }
]

I tried to do something like:

const myObj = arrKeys.reduce((newObj, key, index) => {
  if (arrValues[index] == undefined) arrValues[index] = null
  newObj[key] = aarValues[index]
  return newObj
}, {})
cosnole.log(myObj)

But the problem is, that arrKeys is looping only once and I do not know, how to "reset" the counter each time arrKeys gets to max length. Also I got only an object back, not an array of objects:

My result

myObj = {
  "a": 1,
  "b": 2,
  "c": 3
 }

Any ideas are really appreaciated.

about 4 years ago · Santiago Gelvez
3 Respuestas
Responde la pregunta

0

You can iterate over the values, creating arrKeys.length chunks at a time, and then creating an object from the chunk by mapping the chunk index to the appropriate key. This approach has the advantage that if arrValues is not an exact multiple of arrKeys length, it will still work:

const f = (arrKeys, arrValues) => {
  const result = []
  const kLen = arrKeys.length
  const vLen = arrValues.length
  for (i = 0; i < vLen; i += kLen) {
    chunk = arrValues.slice(i, i + kLen)
    result.push(Object.fromEntries(chunk.map((v, i) => [arrKeys[i], v])))
  }
  return result;
}

console.log(f(["a", "b", "c"], [1, 2, 3, 4, 5, 6, 7, 8, 9]))
console.log(f(["a", "b", "c"], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]))
console.log(f(["a", "b", "c", "d"], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]))

about 4 years ago · Santiago Gelvez Denunciar

0

You can use modulo operator to get check for every keys.length nth element and then add a new object by slicing the values array where the start is current index and end current index + keys.length

const f = (keys, values) => values.reduce((r, e, i) => {
  if (i % keys.length === 0) {
    const index = i / keys.length
    r[index] = values.slice(i, i + keys.length).reduce((r, e, i) => {
      r[keys[i]] = e
      return r
    }, {})
  }

  return r
}, [])

console.log(f(["a", "b", "c"], [1, 2, 3, 4, 5, 6, 7, 8, 9]))
console.log(f(["a", "b", "c", 'g'], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
console.log(f(["a", "b"], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]))

about 4 years ago · Santiago Gelvez Denunciar

0

One way would be to loop through the arrValues using a conventional for...loop.

We can use the modulus operator % to determine where we are in the run of three.

Check the below for a demo:

var arrKeys = ["a", "b", "c"];
var arrValues = [ 1, 2, 3, 4, 5, 6, 7, 8, 9];

var myObj = [];
var newObj = null;
for(var i=0; i<arrValues.length; i++)
{
  if(i % 3 === 0) // First run of three
    newObj = {};

  newObj[ arrKeys[i % 3] ] = arrValues[i];
  
  if(i % 3 === 2) // We're at the end of the run of three
    myObj.push(newObj);
}
console.log(myObj);

about 4 years ago · Santiago Gelvez 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