abyrne85
abyrne85

Reputation: 1460

Destructuring in ES6

Is there a nicer way of achieving this using destructuring in es6?

  searchCreated(searchParams) {
    this.regionId = searchParams.region;
    this.maxPrice = searchParams.maxPrice;
    this.minPrice = searchParams.minPrice;
    this.selectedLocalities = searchParams.selectedLocalities;
    this.propertyTypeId = searchParams.propertyTypeId;
    this.minBeds = searchParams.minBeds;
    this.maxBeds = searchParams.maxBeds;
    this.minSize = searchParams.minSize;
    this.maxSize = searchParams.maxSize;
    this.keyword = searchParams.keyword;
    this.ber = searchParams.ber;
}

If all those values were on their own rather than properties of the this I'd be fine. I'm just not sure of an elegant way of effectively mapping one object onto another

Upvotes: 1

Views: 108

Answers (2)

Ori Drori
Ori Drori

Reputation: 193358

You can use object rest to collect all props except those that need renaming. You can assign new names while destructuring. Then use Object#assign to merge everything into this.

Note: object rest/spread is still a proposal, and it requires a babel transform to work.

searchCreated({ region: regionId, ...otherProps }) {
    return Object.assign(this, otherProps, { regionId });
}

Upvotes: 1

Christian Santos
Christian Santos

Reputation: 5456

Because you are adding all of searchParam's properties to this, you can use Object.assign, which basically copies an object's properties to another object.

In your code, it would look like so:

searchCreated(searchParams) {
    Object.assign(this, searchParams, { // additional object for custom params
        region: searchParams.regionId,
        customParamName: searchParams.customParam
    }); 
}

Upvotes: 3

Related Questions