Search code examples
javascriptnode.jscommonjs

Destructured object loses reference after being modified


Object reference is lost after an assignment. Any previous references are no longer relevant.

I have the following:

// lib.js

const obj = { prop: { data: { some: 'empty' } } };

function loadObject() {
  obj.prop.data = { some: 'load' };
}

modules.exports = { prop: obj.prop, data: obj.prop.data, loadObject() };

and

// main.js

const { prop, data, loadObject } = require('./lib');

loadObject();

console.log(prop.data);    // data changed (new reference)
console.log(data);         // data not changed (old reference)

How can I modify data without losing it's initial reference?

PS:

I have a bunch of files importing this lib and it's relying on that data. I'd rather not replace it to prop.data or reread it again in each file that uses it.


Solution

  • You replaced data with a new object. There’s no way to change everything that references an old object to point to a new object instead, so if you want to keep the exact same API, you have to alter the object in place instead of replacing it – maybe like you did before:

    // if it’s a single property that’s the same before and after
    function loadObject() {
      obj.prop.data.some = 'load';
    }
    
    // if the properties before are a subset of the properties after
    function loadObject() {
      Object.assign(obj.prop.data, { some: 'load' });
    }
    
    // if you need to change the set of properties entirely
    function loadObject() {
      for (const key of Object.keys(obj.prop.data)) {
        delete obj.prop.data[key];
      }
    
      Object.assign(obj.prop.data, { some: 'load' });
    }