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

222
Visualizações
Creating new array of objects from existing arrays, matching on index

I have two arrays, and presently I am combining them into one array like so:

const changeArr = selectedReasons.map((e, i) => e + changeComments[i]);

That works, but what I'd ideally like to do is, rather than mashing them into one element, is create an array of objects, where each object has a property referencing the first array, and the second property being the corresponding index element from the second array.

So imagine the first array looks like this:

selectedReasons = [
  "100A",
  "100B"
]

And the second one looks like this:

changeComments = [
  "Here is my clarifying comment for the first choice.",
  "This is a different comment pertaining to my second choice."
]

What I'd like to end up with is this:

changeArr = [
  {
    reason: "100A",
    comment: "Here is my clarifying comment for the first choice."
  },
  {
    reason: "100B",
    comment: "This is a different comment pertaining to my second choice."
  }
]

How can I adjust my current code which mashes together elements into an array of objects with two properties for each object, that match based on the index of the elements?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could loop from 0 to the end of the reasons array, and push new objects to a new array using the reason and comment at index i from their respective other arrays, like so:

let changeArr = [];
for (let i = 0; i < selectedReasons.length; i++) {
    changeArr.push({ reason: selectedReasons[i], comment: changeComments[i] });
}

This does mean that if the selectedReasons array and the changeComments array are not the same length, you might run into problems

about 4 years ago · Juan Pablo Isaza Relatório

0

You simply need to return an object

var selectedReasons = [
  "100A",
  "100B"
]

var changeComments = [
  "Here is my clarifying comment for the first choice.",
  "This is a different comment pertaining to my second choice."
]


var result = selectedReasons.map((reason, i) => ({
  reason,
  change: changeComments[i]
}))

document.write(`<pre>${JSON.stringify(result, null, 2)}</pre>`)

about 4 years ago · Juan Pablo Isaza 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