Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!