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

118
Visualizações
Update the value of nested object in the array based on the key

i have two array of objects like below, am trying to compare two arrays and looking to update the object total value of arr1 if the id matches with arr2.

const arr1 = [
{
  id: 1,
  value: { total: 0 },
},
{
  id: 2,
  value: { total: 0 },
},
{
  id: 3,
  value: { total: 0 },
},
 id: 4,
  value: { total: 0 },
},
];

const arr2 = [
    {
      id: 2,
      value: 3 ,
    },
    {
      id: 3,
      value: 5,
    },

  ];

I am trying to compare two arrays and looking to update the object total value of arr1 if the id matches with arr2

expected result is

const arr1 = [
 {
  id: 1,
 value: { total: 0 },
 },
{
id: 2,
value: { total: 3 },
},
{
 id: 3,
 value: { total: 5 },
 },
 {
  id: 4,
  value: { total: 0 },
 },
 ];

I have tried the below code,

arr1.map((item) => {
arr2.find((element) => {
  if (element.id === item.id ) {
    item = {
      ...item,
      value: {
        ...item.value,
        total: item.value.total + element.value,
      },
    };
    console.log(item);
  }
});
return item;
});
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I have changed the find function to the filter function and will add the result to the original array.

try this

const arr1 = [
{
  id: 1,
  value: { total: 0 },
},
{
  id: 2,
  value: { total: 0 },
},
{
  id: 3,
  value: { total: 0 },
},
{
  id: 4,
  value: { total: 0 },
}
]
const arr2 = [
    {
      id: 2,
      value: 3 ,
    },
    {
      id: 3,
      value: 5,
    },
  ];
  
arr1.map((item) => {
  let result = arr2.filter((element) => element.id == item.id)
  if(result && result.length) {
    item.value.total += result[0].value
  }
  return item;
});  


console.log(arr1)

about 4 years ago · Juan Pablo Isaza Relatório

0

You have to assign map to your array:

  this.arr1 = this.arr1.map((item) => {
      this.arr2.find((element) => {
        if (element.id === item.id) {
          item = {

            ...item,
            value: {
              ...item.value,
              total: item.value.total + element.value,
            },
          };
          console.log(item);
        }
      });
      return item;
    });
about 4 years ago · Juan Pablo Isaza Relatório

0

If each object's id is unique (within each array), you can do:

arr1.forEach((obj1) => {
  const obj2Match = arr2.find((obj2) => obj1.id === obj2.id );

  if (obj2Match) {
    obj1.value.total += obj2Match.value;
  }
});

If more than one object can have the same id (e.g. arr2 has two objects that have the id of 2), then you can do:

arr1.forEach((obj1) => {
  const obj2Matches = arr2.filter((obj2) => obj1.id === obj2.id );

  if (obj2Matches.length) {
    obj1.value.total += obj2Matches.reduce(((accum, curr) => accum  + curr.value), 0);
  }
});

Complexity:

  • Time: O(N * M)
  • Space: O(M)
  • N => arr1.length, M => arr2.length
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