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

120
Visualizações
Combining the content of multiple objects that have the same key with that key as the property in JavaScript

I want to combine the content of multiple objects that have the same key with that key as the property in JavaScript.

Objects:

const cat1 = { med1: { a: 10, b: 12 }, med2: { c: 14, d: 16 } };

const cat2 = { med1: { e: 18, f: 20 }, med2: { g: 22, h: 24 } };

Expected output:

{
   med1: { a: 10, b: 12, e: 18, f: 20 }, 
   med2: { c: 14, d: 16, g: 22, h: 24 }
}

I have tried to use both object spreading and Object.assign with no sucess. With object spreading, since objects have no iterator this is returning an error. Object.assign would work however since the two objects to combine have the same key, the second object is overwriting the first.

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

0

You can iterate over the object keys and create a new object out of their aggregation.

You can use ES6 spread operator (...) which allows us to quickly copy all or part of an existing array or object into another array or object.

const cat1 = { med1: { a: 10, b: 12 }, med2: { c: 14, d: 16 } };
const cat2 = { med1: { e: 18, f: 20 }, med2: { g: 22, h: 24 } };
let resultObject = {};
Object.keys(cat1).map(key => { // iterate over the keys
  resultObject = {
    ...resultObject,
    [key]: {...cat1[key], ...cat2[key]} // merge two objects 
  }
  return;
});

console.log(resultObject);

about 4 years ago · Juan Pablo Isaza Relatório

0

For combining two objects with a single level of indirection 👇

const cat1 = { med1: { a: 10, b: 12 }, med2: { c: 14, d: 16 } }
const cat2 = { med1: { e: 18, f: 20 }, med2: { g: 22, h: 24 } }

const merge = (o1, o2) =>
    Object.keys(o1)
        .reduce((p, key) => 
            (p[key] = { ...o1[key], ...o2[key] }, p), {})

console.log(merge(cat1, cat2))

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