0

I'm wondering if there's a way to use destructuring in order to copy all properties of an object into this without knowing the props.

class MyObject {
  constructor(data) {
    this.someFlag = true

    // How can I destructure 'data' into this.
  }
}

I've seen this answer (and some other) but they all have in common the knowledge of the properties to be copied or the usage of Object.assign. I'm wondering how to do it using simple destructuring.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
fredmaggiowski
  • 2,232
  • 3
  • 25
  • 44
  • 1
    Destructuring doesn't work if you don't know the properties? Not sure what you are trying to achieve, when your `Object.assign` solution already works. – Bergi Jul 09 '19 at 12:22
  • Object.keys(data).forEach(key => this[key] = data[key]) – Roland Jul 09 '19 at 12:24
  • 7
    @roliroli `Object.assign(this, data);` – Thomas Jul 09 '19 at 12:25
  • @Bergi I'm just wondering whether is it possible to exploit destructuring operators to do this. – fredmaggiowski Jul 09 '19 at 12:26
  • 1
    What would be the use in doing so? You would need to know the properties beforehand. – Kobe Jul 09 '19 at 12:28
  • @FredMaggiowski `for (const k in data) {[k]: this[k]} = data` is the best I can think of that achieves what you need and still uses destructuring. There is no syntax to have a target for multiple properties. – Bergi Jul 09 '19 at 12:28
  • 1
    @FredMaggiowski the only thing you can do with object destructuring, without knowing the properties, is making a shallow copy: `const { ...copy } = data;` of which you still don't know the properties. And NO, you can't put `this` in there, as `this` is no t a valid name for a variable. – Thomas Jul 09 '19 at 12:29
  • You can use `{...this, ...data}` to merge the two objects but you can't redefine `this` to this value – frobinsonj Jul 09 '19 at 12:31
  • @Kobe no actual use, I've recently started using javascript after a few years and now that I'm studying the new stuff they introduced with ES6 I'm having questions that needs to be answered :) – fredmaggiowski Jul 09 '19 at 12:48
  • Yeah, I've thought about what @frobinsonj suggested in order to something like `this = {...this, ...data }` but felt dirty because it rewrites the entire `this`. – fredmaggiowski Jul 09 '19 at 12:50
  • 1
    even with modern ES, `this = ...` is still not possible in JS. – Thomas Jul 09 '19 at 12:51
  • @Thomas true, indeed.. – fredmaggiowski Jul 09 '19 at 12:52
  • *in modern JS* ... Why would `Object.assign` be old-fashioned? It works (great) – Jonas Wilms Jul 09 '19 at 14:19

1 Answers1

3

No, you can't use destructuring, as that would be used in redefining this which you can't do. Either go with Object.assign:

Object.assign(this, data);

Or if you really want to use destructuring some way or another:

Object.entries(data).forEach(([k, v]) => this[k] = v);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79