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

108
Visualizações
I have two objects and i need to merge them and concat strings if two props have the same key

I have two objects and i need to merge them and concat strings if two props have the same key note: I'm using lodash.js

obj1 = {
  name: 'john', 
  address: 'cairo'
}

obj2 = {
  num : '1', 
  address: 'egypt'
}

I need the merged object to be like:

merged = {name:"john", num: "1", address:"cairo,Egypt"}

the issue with address prop when I'm trying to use _.defaults(obj1,obj2) or _.merge(obj1,obj2)

the address value will be the value of the address prop inside obj2 so I need a way to merge the two objects and concat the two address props in each object.

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

0

Try this:

    function merge(obj1, obj2) {
      let merged = {
        ...obj1,
        ...obj2
      };
      Object.keys(obj1).filter(k => obj2.hasOwnProperty(k)).forEach((k) => {
        merged[k] = obj1[k] + "," + obj2[k]
      })
      return merged
    }

    obj1 = {
      name: 'john',
      address: 'cairo'
    }

    obj2 = {
      num: '1',
      address: 'egypt'
    }

    console.log(merge(obj1, obj2))

about 4 years ago · Juan Pablo Isaza Relatório

0

function mergeObjects(objArr) {
    const newObj = {};

    objArr.forEach((element) => {
        const keys = Object.keys(element);
        keys.forEach((key) => {
            if (newObj[key]) newObj[key] = newObj[key] + "," + element[key];
            else newObj[key] = element[key];
        });
    });
    return newObj;
}

const obj1 = {name: 'john',   address: 'cairo'}

const obj2 = {  num : '1',   address: 'egypt'}
console.log(mergeObjects([obj1, obj2]));

This way you can merge any number of objects!

about 4 years ago · Juan Pablo Isaza Relatório

0

You don't even need lodash. You can easily create you own function for that. You can do it like this:

  • new Set - to find all unique keys across both input objects
  • for...of - to iterate over unique keys calculated above

function mergeObjects(obj1, obj2) {
  let merged = {};
  for (const property of [...new Set([...Object.keys(obj1),...Object.keys(obj2)])]) {
    if(obj1[property]) merged[property] = obj1[property];
    if(obj2[property]) merged[property] = merged[property] ? `${merged[property]},${obj2[property]}` : obj2[property];
  }
  return merged;
}

const obj1 = { name: 'john', address: 'cairo' };
const obj2 = { num : '1', address: 'egypt' };

const mergedObj = mergeObjects(obj1, obj2);
console.log(mergedObj);

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