Reputation: 1460
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
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
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