对象解构为对象声明? [英] Object deconstruction into object declaration?

查看:109
本文介绍了对象解构为对象声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,它有几个我想要提取的值,并放入另一个具有不同键的对象中。现在我正在使用解构来提取值,然后用提取的值及其新键定义一个对象文字。

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.

这是我的函数:

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?

推荐答案

我认为没有任何内容可以放在同一个声明中,尤其是重命名时。您当然可以编写自己的辅助函数来重命名对象属性。

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

如果你<你也可以使用解构到对象属性来交换双方sup> 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:我个人认为这只是不必要的混淆 - 一行更长!

这篇关于对象解构为对象声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆