Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

277
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda