Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

javascript - Object deconstruction into object declaration?

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 extract the values, then defining an object literal with those extracted values and their new keys.

Here is my function:

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
    };
}

However, I was wondering if is a shorthand way to do this, so use one line for both the deconstruction and the declaration. Does anyone know if this is possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...