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

249
Views
JavaScript - Is it possible to copy primitive object properties by reference?

I want to create a new object that has properties that reference properties from other objects. I want modifying new object properties to also update the original source object properties.

const obj1 = {
    a: 1,
}

const obj2 = {
    b: 2,
}

const newObj = {...obj1, ...obj2};
newObj.a = 3;

// obj1.a should also be set to 3

I think this can be achieved via getters and setters, but is it possible to create get/set dynamically from property keys of another object?

Thanks!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can create a Map of objects to reference, and then create a Proxy to add / update / get values from the Map:

const obj1 = {
  a: 1,
}

const obj2 = {
  b: 2,
}

const objects = new Map([obj1, obj2].flatMap(o => 
  Object.keys(o).map(k => [k, o])
))

const newObj = new Proxy(objects, {
  get(target, prop) {  
    if (prop === 'toJSON') {
      return () => Object.assign({}, ...target.values())
    }
  
    const obj = target.get(prop)
    
    return obj ? obj[prop] : undefined
  },
  set(target, prop, value) {  
    const obj = target.get(prop)
    
    if(!obj) {
      target.set(prop, {})
    }
    
    obj[prop] = value
    
    return true
  },
  has(target, prop) {
    return target.has(prop);
  },
  ownKeys() {
    return [...target.keys()]
  }
})

newObj.a = 3
newObj.b = 5

console.log({ obj1 })
console.log({ obj2 })
console.log({ newObj })

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!