Home > Enterprise >  How to achieve shallow copy of destructured object in JS
How to achieve shallow copy of destructured object in JS

Time:05-06

Im trying to figure out what is the best way to achieve a reconstructed "destructured" shallow copy of an object. I mean, how can I get a referenced object with only a subset of keys, but who are connected to the original object? From let original={ a=1, b=2, c=3} to a reference connected let reconstructed= { a=1, c=3}... values of keys are strings or numbers. I tried workarounds but cannot get a comfortable solution for this. Help would be appreciated.

CodePudding user response:

You could use an array containing the props you want, and then hacky nonsense with getters and setters to build an object that actually reads from/writes to a different object.

Note: I've never needed to do this. I think you might have better luck with a different general approach, like "Use the same object, but only display the properties that are appropriate instead of all of them".

let original={ a:1, b:2, c:3};
let propsInNewObject = ["a", "c"];

const reconstructed = propsInNewObject.reduce((obj, el) => {
  Object.defineProperty(obj, el, { 
    get: () => original[el],
    set: (value) => { original[el] = value },
    enumerable: true
  });
  return obj;
}, {});

console.log(reconstructed, original);
reconstructed.a = 100;
console.log(reconstructed, original);

CodePudding user response:

This might be the wrong answer because your question is unclear, especially regards which bit is the 'shallow' copy.

Your reconstructed object is a new, independent object, and not connected to the source object in any way.

let reconstructed = { a, b }
           //       ^      ^
           //       denotes a new object

The question is, what types might a and b, be? If the properties deconstructed from the source object are themselves references (other objects), then modifying the deconstructed value, either in its independent state, or when assigned to the reconstructed object, will change the source value too.

let foo = { a: 1, b: 2 }
let { a, b } = foo
a = 999
console.log(foo, a, b)

let bar = { baz: { msg: 'Hello World' } }
let { baz } = bar
let bar1 = { baz }
baz.msg = 'Hello Sailor'
console.log(bar, baz, bar1)

  • Related