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

153
Visualizações
How to merge two Objects and keep the hierarchy between properties?

I have a question about the two objects above:

const object1 = { issues: { global: 'a great string!' } };
const object2 = { issues: { cooldown: 'oh well, another message!' } };


For the purpose of my code, I would need to merge everything but keep the hierarchy between the properties. Like this:

Object.assign(object1, object2);
console.log(object1);
// expected output: { issues: { global: 'a great string!', cooldown: 'oh well, another message!' } }


Except that the problem is that the Object.assign() works such that it will overwrite the previous property (here global) to keep only the last property (here cooldown). Like this:

Object.assign(object1, object2);
console.log(object1);
// real output: { issues: { cooldown: 'oh well, another message!' } }


My question is then simple: how do we get the expected result? I guess it's not as simple as a simple Object.assign(), but precisely: how? Knowing that obviously I took here an example and that, in reality, impossible to know in advance which properties will arrive...

Thanking you for help 💙

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

0

I think a recursive solution will help for any level of nesting:

const obj1 = { issues: { global: 'a great string!' } };
const obj2 = { issues: { cooldown: 'oh well, another message!' } };

const obj3 = { issues: { global: 'a great string!' } , problems : { name : 'cool' , size : {
  medium : 'ok',
  small : 'ok'
} } };
const obj4 = { issues: { cooldown: 'oh well, another message!' } , problems : { name : 'cool' , size : {
  big : 'not ok',
} }  };



const merge = (obj1,obj2) => {
  const newObj = {};
  for(let key in obj1){
    if(typeof obj1[key] !== 'object'){
      newObj[key] = obj1[key]; 
    }
    else
  if(key in obj2){
    newObj[key] = merge(obj1[key],obj2[key]);
  }
  else{
   newObj[key] = obj1[key];
   }
  }
  for(let key in obj2){
  if(!(key in obj1)){
    newObj[key] = obj2[key];
  }
  }
  return newObj;    
};

console.log(merge(obj1,obj2));
console.log(merge(obj3,obj4));

You check if keys are matching (available in both objects) and based on that add a new key to your new result object.

Note: The above by defaults handle case when the property values are not objects. You can change and add your desired behaviour

about 4 years ago · Juan Pablo Isaza Relatório

0

i create this function i think it will do the work

const obj1 = { issues: { global: 'a great string!' } };
const obj2 = { issues: { cooldown: 'oh well, another message!' } };

const obj3 = {
    issues: { global: 'a great string!' }, problems: {
        name: 'cool', size: {
            medium: 'ok',
            small: 'ok'
        }
    }
};
const obj4 = {
    issues: { cooldown: 'oh well, another message!' }, problems: {
        name: 'cool', size: {
            big: 'not ok',
        }
    }
};

const mergeObj = (obj1, obj2) => {
    const Obj1Keys = Object.keys(obj1)
    const Obj2Keys = Object.keys(obj1)
    const allKeys = [...new Set([...Obj1Keys, ...Obj2Keys])]
    const newObj = {}
    for (let i = 0; i < allKeys.length; i++) {
        const key = allKeys[i]
        if (typeof obj1[key] === "object" && typeof obj2[key] === "object")
            newObj[key] = mergeObj(obj1[key], obj2[key])
    }
    return Object.assign(obj1, obj2, newObj)
}
console.log(mergeObj(obj3, obj4));

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