ES6动态解构

时间:2018-10-10 14:02:03

标签: javascript typescript ecmascript-6

我需要根据全局标志(针对多个应用的​​单个服务)对功能响应应用不同的解构方法

// Destructuring template should be defined as value
let destructuringTemplate;
if (flag) {
   destructuringTemplate = {data: {classA: user}};
} else {
   destructuringTemplate = {data: {classB: user}};
}
// This technique would not work, this is just my idea representation.
this.getUser(({destructuringTemplate: user) => { this.localUser = user });

目前,它是这样工作的:

let destructuringTemplate;
if (flag) {
   destructuringTemplate = ({data: {classA: user}}) => user;
} else {
   destructuringTemplate = ({data: {classB: user}}) => user;
}
this.getUser(response => { this.localUser = destructuringTemplate(response)};

有点丑陋,有些建议应该怎么做?

2 个答案:

答案 0 :(得分:5)

您可以将computed property nameconditional (ternary) operator ?:结合使用。

var autocompleParam = {
    offset: 3
}    

google.maps.event.addListener(to_address, 'place_changed', function (e) {
    if (to_address.value.length < autocompleParam.offset) {
        return;
    }
    var place = to_address.getPlace();
    document.getElementById('end_location').style.borderColor = '';
    attr.props.onChangeEndLocationSearch(place.place_id);
    attr.props.onReturnLocation(e);
});

答案 1 :(得分:0)

您不需要使用解构,只需使用简单的点/括号表示法即可:

const userClass = flag ? 'classA' : 'classB'
this.getUser(response => { this.localUser = response.data[userClass] })

如果您想重用此逻辑,只需创建简单的函数,例如:

const extractUser = response => response.data[userClass]