Object Deconstruction Into Object Declaration?
Solution 1:
I don't think there's anything to put them in the same statement, especially with the renaming. You could of course write your own helper function for renaming object properties.
I think it would be much cleaner though to assign the object to one variable and then repeat that multiple times, than repeating every property/variable name twice:
getProductReviewData() {
const all = this.productReviewsStore.getAll();
return {
ratingDisplay: all.averageRateDisplay,
rating: all.rawAverageRate,
ratingCount: all.displayReviewCount,
reviewIds: all.productReviewIds,
reviewMap: all.productReviews
};
}
You can also use destructuring into object properties to swap the two sides if you like that better:
getProductReviewData() {
let res = {};
({
averageRateDisplay: res.ratingDisplay,
rawAverageRate: res.rating,
displayReviewCount: res.ratingCount,
productReviewIds: res.reviewIds,
productReviews: res.reviewMap
} = this.productReviewsStore.getAll());
return res;
}
1: Personally I think it's just unnecessary confusing - and one line longer!
Solution 2:
You can destructure and give new key/variable values in one go. But as far as I know you can't destructure directly into a new object.
const start = {
averageRateDisplay: 1,
rawAverageRate: 2,
displayReviewCount: 3,
productReviewIds: 4,
productReviews: 5
};
// destructuring with renaming of variablesconst {
// name to match : newName
averageRateDisplay: ratingDisplay,
rawAverageRate: rating,
displayReviewCount: ratingCount,
productReviewIds: reviewIds,
productReviews: reviewMap
} = start;
// creating new object, using property value shorthand// https://ariya.io/2013/02/es6-and-object-literal-property-value-shorthandconst end = {
ratingDisplay,
rating,
ratingCount,
reviewIds,
reviewMap
};
console.log(end)
Solution 3:
UPD: Simple is better than complex! I like Bergi's answer =)
Probably you can declare new keys and then change them in iterations ¯_(ツ)_/¯
getProductReviewData() {
//declare new keysconst newKeys = {
averageRateDisplay: "ratingDisplay",
rawAverageRate: "rating",
displayReviewCount: "ratingCount",
productReviewIds: "reviewIds",
productReviews: "reviewMap"
}
const productReviewsStore = this.productReviewsStore.getAll();
//return the object with replaced keysreturnObject.assign({},
...Object.keys(productReviewsStore)
.filter(key => newKeys[key])
.map(key => ({[newKeys[key]]: productReviewsStore[key]}))
)
}
Post a Comment for "Object Deconstruction Into Object Declaration?"