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

107
Visualizações
Merge two objects but not all properties

I am struggling to merge two objects the way I need them using Node.js express and mongoDB. Below you will see both initial objects.

Obj1: {
           "name":"max",
           "age":26,
           "hometown": "NY"
    }
Obj2: {
       "id": "123",
       "favoriteteams" : ["Yankees, "Knicks"],
       "home" : "NY"
    }

I am currently trying:

const merged = {...obj1, ...obj2.favoriteteams}; 

But that gives me

merged: {
       0: "Yankees"
       1: "Knicks"
       "name":"max",
        "age":26,
        "hometown": "NY"
    }

But what I need is:

merged: {
       "name":"max",
        "age":26,
        "hometown": "NY"
        "favoriteteams": ["Yankees", "Knicks"];
    }

I also have tried const merged = {...obj1, ...obj2}; and using Object.assign() but both obviously then mesh in the fields I don't need from obj2 (ID and home). Effectively I only need to get the favoriteteams from the second object, but I need that to be a new key in the first object and also to maintain the array response with the list of strings.

Thank you for any help.

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

0

You can leverage $mergeObjects in MongoDB aggregation.

db.collection.aggregate([
  // keep only the fields you want in obj2
  {
    "$project": {
      favoriteteams: 1
    }
  },
  {
    "$addFields": {
      obj2: "$$ROOT",
      obj1: <put your obj1 here>
    }
  },
  {
    "$project": {
      // perform merge
      merged: {
        "$mergeObjects": [
          "$obj1",
          "$obj2"
        ]
      }
    }
  },
  {
    "$replaceRoot": {
      // revert back to original form
      "newRoot": "$merged"
    }
  }
])

Here is the Mongo playground for your reference.

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