1

I'm constantly confused whether object destructuring in javascript applies in certain situations, and I've just come across one. In this code I am simply taking properties from the this object and assigning them to the same property/value on a new data object:

const data = {
    rating: this.rating,
    title: this.title,
    text: this.text,
    name: this.name,
    location: this.location,
    email: this.email,
    files: this.files
};

Can some sort of object destructuring be used to accomplish this instead or is it unrelated to this use-case?

flyingL123
  • 7,686
  • 11
  • 66
  • 135

2 Answers2

5

You can use the spread operator if you want all the own properties of this:

const data = {
  ...this
}

If you only need a selective few, you can delete the unnecessary properties afterwards, or set them to undefined (although that's different from non-existent/deleted properties):

const data = {
  ...this,
  unwantedProp: undefined,
}
wilsonzlin
  • 2,154
  • 1
  • 12
  • 22
2

You could use something like this

const choose = (src, ...keys) => keys.reduce((result, key) => ({ ...result, [key]: src[key] }), {});

example usage

const choose = (src, ...keys) => keys.reduce((result, key) => ({ ...result, [key]: src[key] }), {});


const src = {
    rating: 1,
    title: 2,
    text: 3,
    name: 4,
    location: 5,
    email: 6,
    files: 7,
    not_me: 8
};

const data = choose(src, 'rating', 'title', 'text', 'name', 'location', 'email', 'files');
console.log(data);

In your case, you'd use this instead of src when calling choose

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • 1
    Very cool solution. Though I was more curious if there was a simple way to do this inline with destructuring. I was not looking to create a new function like you have with `choose`. Seems like the answer may just be "no". – flyingL123 Oct 04 '18 at 02:00
  • No, can't think of anything without creating a function – Jaromanda X Oct 04 '18 at 02:04