0

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!

1

1 Answer 1

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 })

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.