是否可以进行有条件的销毁或回退? [英] Is it possible to do conditional destructuring or have a fallback?

查看:79
本文介绍了是否可以进行有条件的销毁或回退?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有很多深层嵌套属性的对象.我希望能够访问"MY_KEY"(如下)上的属性,但是如果该属性不存在,请获取"MY_OTHER_KEY".我该怎么办?

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". 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

首先,这种解构将一直尝试提取第二个密钥,这可能会带来一些意想不到的影响,例如MY_OTHER_KEY的属性获取器将始终运行.

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.

但是我看不到其中的美丽.将某些控制流隐藏在解构内部只是令人困惑.我宁愿建议提取父对象并对其使用常规属性访问:

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

这篇关于是否可以进行有条件的销毁或回退?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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