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

243
Views
javascript Object.assign() without overriding fields

Is there any way to merge two objects, like Object.assign(a, b), but I want the same field in a keeps its origin value (without overriding from b).

a = {x: 1, y: 2}
b = {y: 3, z: 4}

Object.assign(a, b)
// Now we get a = {x: 1, y: 3, z: 4}, so what if I want {x: 1, y: 2, z: 4}?
console.log(a) 
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

The best solution to this is to avoid using Object.assign and use spread operator as by doing so you'll achieve your goal with simple logic. In spread operator, the rightmost element overwrites the left one.

a = {x: 1, y: 2};
b = {y: 3, z: 4};
        
result = {...b, ...a}; 
result2 = {...a, ...b};

console.log(result); // {x: 1, y: 2, z: 4} 
console.log(result2); // {x: 1, y: 3, z: 4} 
about 4 years ago · Juan Pablo Isaza Report

0

let a = { x: 1, y: 2 };
let temp = { ...a };
let b = { y: 3, z: 4 };

Object.assign(a, b);
Object.assign(a, temp);

console.log(a);

about 4 years ago · Juan Pablo Isaza Report

0

You could use Object.entries and filter out keys that are already in a.

eg.

a = {x: 1, y: 2}
b = {y: 3, z: 4}

//Object.assign(a, b)
// Now we get a = {x: 1, y: 3, z: 4}, so what if I want {x: 1, y: 2, z: 4}?
Object.assign(a, Object.fromEntries(
  Object.entries(b).
    filter(([k])=>!(k in a))));

console.log(a) 

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!