我有一个对象,它有几个我想要提取的值,并放入另一个具有不同键的对象中。现在我正在使用解构来提取值,然后使用提取的值及其新键定义对象文字。
这是我的功能:
getProductReviewData() {
const {
averageRateDisplay,
rawAverageRate,
displayReviewCount,
productReviewIds,
productReviews
} = this.productReviewsStore.getAll(); // this is deconstruction of an object
return {
ratingDisplay: averageRateDisplay,
rating: rawAverageRate,
ratingCount: displayReviewCount,
reviewIds: productReviewIds,
reviewMap: productReviews
};
}
然而,我想知道这是否是一种速记方式,所以在解构和声明中使用一行。有谁知道这是否可行?
答案 0 :(得分:4)
I don't think there's anything to put them in the same statement,特别是重命名。您当然可以编写自己的辅助函数来重命名对象属性。
我认为将对象分配给一个变量然后重复多次会比重复每个属性/变量名两次要清晰得多:
getProductReviewData() {
const all = this.productReviewsStore.getAll();
return {
ratingDisplay: all.averageRateDisplay,
rating: all.rawAverageRate,
ratingCount: all.displayReviewCount,
reviewIds: all.productReviewIds,
reviewMap: all.productReviews
};
}
如果您更好地 1 ,您还可以使用解构到对象属性来交换双方:
getProductReviewData() {
let res = {};
({
averageRateDisplay: res.ratingDisplay,
rawAverageRate: res.rating,
displayReviewCount: res.ratingCount,
productReviewIds: res.reviewIds,
productReviews: res.reviewMap
} = this.productReviewsStore.getAll());
return res;
}
1:就我个人而言,我认为这只是一种不必要的混淆 - 而且还会延长一行!
答案 1 :(得分:0)
UPD:简单比复杂更好!我喜欢Bergi's answer =)
可能你可以声明新的密钥,然后在迭代中改变它们¯_(ツ)_ /¯
getProductReviewData() {
//declare new keys
const newKeys = {
averageRateDisplay: "ratingDisplay",
rawAverageRate: "rating",
displayReviewCount: "ratingCount",
productReviewIds: "reviewIds",
productReviews: "reviewMap"
}
const productReviewsStore = this.productReviewsStore.getAll();
//return the object with replaced keys
return Object.assign({},
...Object.keys(productReviewsStore)
.filter(key => newKeys[key])
.map(key => ({[newKeys[key]]: productReviewsStore[key]}))
)
}
答案 2 :(得分:0)
您可以一次性构造并提供新的键/变量值。但据我所知,你不能直接解构成一个新的对象。
const start = {
averageRateDisplay: 1,
rawAverageRate: 2,
displayReviewCount: 3,
productReviewIds: 4,
productReviews: 5
};
// destructuring with renaming of variables
const {
// 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-shorthand
const end = {
ratingDisplay,
rating,
ratingCount,
reviewIds,
reviewMap
};
console.log(end)