Object deconstruction into object declaration?

前端 未结 3 2129
野性不改
野性不改 2020-12-21 21:06

I have an object which has several values I want to extract and place into another object with different keys for those values. Right now I\'m using deconstruction to extrac

3条回答
  •  遥遥无期
    2020-12-21 21:33

    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 you1 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!

提交回复
热议问题