[英]ES6 dynamic destructuring
I need to apply different destructuring for the function response depending of global flag [single service for multiple apps] 我需要根据全局标志对函数响应应用不同的解构[多个应用程序的单个服务]
// 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 });
At this moment it works this way: 目前,它是这样工作的:
let destructuringTemplate;
if (flag) {
destructuringTemplate = ({data: {classA: user}}) => user;
} else {
destructuringTemplate = ({data: {classB: user}}) => user;
}
this.getUser(response => { this.localUser = destructuringTemplate(response)};
it is kinda ugly, some suggestion how it should be done? 这有点丑陋,有些建议应该怎么做?
You could use a computed property name with a conditional (ternary) operator ?:
. 您可以将计算的属性名称与条件(三元)运算符?:
。
var flag = true, object = { data: { classA: 'foo', classB: 'bar' } }, { data: { [flag ? 'classA' : 'classB']: user } } = object, { data: { [!flag ? 'classA' : 'classB']: user1 } } = object; console.log(user); console.log(user1);
You don't need to use destructuring, use simple dot/bracket notation: 您不需要使用解构,只需使用简单的点/括号表示法即可:
const userClass = flag ? 'classA' : 'classB'
this.getUser(response => { this.localUser = response.data[userClass] })
If you want to reuse this logic, just create simple function, eg: 如果要重用此逻辑,只需创建简单的函数,例如:
const extractUser = response => response.data[userClass]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.