Home > Software engineering >  JavaScript - Is it possible to copy primitive object properties by reference?
JavaScript - Is it possible to copy primitive object properties by reference?

Time:10-16

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!

CodePudding user response:

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 })
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related