简体   繁体   English

是否可以进行条件性销毁或回退?

[英]Is it possible to do conditional destructuring or have a fallback?

I have an object that has lots of deeply nested properties. 我有一个具有很多深层嵌套属性的对象。 I want to be able to access properties on "MY_KEY" (below), but if that doesn't exist then get "MY_OTHER_KEY". 我希望能够访问“ MY_KEY”(如下)上的属性,但是如果不存在,请获取“ MY_OTHER_KEY”。 How can I accomplish that? 我该怎么做?

const {
  X: {
    Y: {
      MY_KEY: {
        Values: segments = []
      } = {}
    } = {}
  } = {}
} = segment;

You could achieve this using a temporal variable inside your destructuring assignment, something like this: 您可以在解构分配中使用时间变量来实现此目标,如下所示:

 function destructure(segments) { const { X: { Y: { MY_OTHER_KEY: _fallback_value = {}, MY_KEY: { Values: segment = [] } = _fallback_value, } = {}, } = {}, } = segments; return segment; } console.log(destructure({})); // [] console.log(destructure({X:{}})); // [] console.log(destructure({X:{Y:{MY_KEY:{Values:"A"}}}})); // A console.log(destructure({X:{Y:{MY_OTHER_KEY:{Values:"B"}}}})); // B console.log(destructure({X:{Y:{MY_OTHER_KEY:{Values:"C"}, MY_KEY:{Values:"D"}}}})); // D 

First of all, this kind of destructuring will attempt to extract the second key all the time, which might have some unintended implications, like a property getter for MY_OTHER_KEY will always run. 首先,这种解构将一直尝试提取第二个键,这可能会带来一些意想不到的影响,例如MY_OTHER_KEY的属性获取MY_OTHER_KEY将始终运行。

However I fail to see the beauty in it. 但是我看不到其中的美丽。 Hiding some control flow inside destructuring is just confusing. 将某些控制流隐藏在解构内部只是令人困惑。 I would rather suggest extracting the parent object and use regular property access on it: 我宁愿建议提取父对象并对其使用常规属性访问:

 function destructure(segments) { const { X: { Y: nested = {}, } = {}, } = segments; const selected = nested.MY_KEY || nested.MY_OTHER_KEY || {}; const { Values: segment = [] } = selected; return segment; } console.log(destructure({})); // [] console.log(destructure({X:{}})); // [] console.log(destructure({X:{Y:{MY_KEY:{Values:"A"}}}})); // A console.log(destructure({X:{Y:{MY_OTHER_KEY:{Values:"B"}}}})); // B console.log(destructure({X:{Y:{MY_OTHER_KEY:{Values:"C"}, MY_KEY:{Values:"D"}}}})); // D 

Check if the target is defined 检查目标是否已定义

let {/* do destructuring stuff */}

if (MY_KEY === undefined) {
  // define `MY_OTHER_KEY` variable here
}

If you are trying to assign target to a different property if the previous target definition is undefined you can assign the variable at subsequent target definition 如果在先前的目标定义undefined情况下尝试将目标分配给其他属性,则可以在后续的目标定义中分配变量

 const segment = {Y:123}; let or = "Y"; let X; ({X, X = X || segment[or]} = segment); console.log(X); 

While object destructuring is cool and new, it is not the best in all cases. 虽然对象分解很酷而且很新,但并不是在所有情况下都是最好的。 May do: 可以做:

try {   
  var segments = segment.X.Y.MY_KEY.Values;
} catch(e){
 //whatever
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM