Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

254
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda