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

151
Visualizações
Merge array into an array of an objects

I have an array and an object that has an array as one of its keys. I want to use Lodash to merge the array into the object replace its array. Here is the code...

array1 = [false, true, true];

object1 = {
 id: 1,
 label: 'lorem',
 description: "ipsum",
 users: [
   {
     id: 1,
     user: 'morbi',
     checked: true
   },
   {
     id: 2,
     user: 'mauris',
     checked: true
   },
   {
     id: 3,
     user: 'duis',
     checked: true
   }
 ]
}

What I want to do is have the booleans in array1 replace the "checked" booleans in the users array in object1. I want to use Lodash to do this since it seems like it would be much easier, but if there's another way, I'm open to that.

Any suggestions?

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

0

Given that the arrays are of the same length, you can do this using Array#forEach (or _.forEach):

const 
  array1 = [false, true, true],
  object1 = {
    id: 1,
    label: 'lorem',
    description: "ipsum",
    users: [
      { id: 1, user: 'morbi', checked: true },
      { id: 2, user: 'mauris', checked: true },
      { id: 3, user: 'duis', checked: true }
   ]
};

object1.users.forEach((user, i) => user.checked = array1[i]);

console.log(object1.users);

about 4 years ago · Juan Pablo Isaza Relatório

0

Majed's answer is correct. I'm adding this code here just in case you need to deal with immutability and requires to create new object to trigger changes.

const 
  array1 = [false, true, true],
  object1 = {
    id: 1,
    label: 'lorem',
    description: "ipsum",
    users: [
      { id: 1, user: 'morbi', checked: true },
      { id: 2, user: 'mauris', checked: true },
      { id: 3, user: 'duis', checked: true }
   ]
};

function updateAnswer(obj, answers) {
  return {
    ...obj,
    users: obj.users.map((user, index) => {
      return { ...user, checked: answers[index] }
    })
  }
}

console.log(updateAnswer(object1, array1));

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