【问题标题】:Destructuring nested objects: How to get parent and its children values?解构嵌套对象:如何获取父级及其子级值?
【发布时间】:2019-02-08 11:19:32
【问题描述】:

下面的函数接收一个具有current属性的对象,该对象也是一个对象,具有selectionStartselectionEnd属性。

在这里,StartEnd 变量的嵌套解构按预期工作,但我还需要 current 的值。

function someFunction({ current: { selectionStart: Start, selectionEnd: End } }) {

    // do something with current, Start, and End
}

如何使用解构获得它?

【问题讨论】:

  • 我知道我可以通过解构进入对象的深层,但我找不到如何获取对象本身的值,而不是它的属性。所以在这种特殊情况下,我不知道如何获取 current 的值。
  • 您应该尝试更好地表达您的问题,以澄清StartEnd 工作正常,但current 未定义。 @adiga 刚刚回答了这个问题。
  • @caesay,现在清楚了吗?如果不是,请告诉我。谢谢。

标签: javascript destructuring


【解决方案1】:

第一次解构只创建StartEnd 变量。如果要创建current作为变量,则需要再次声明。

function ({ current: { selectionStart: Start, selectionEnd: End }, current }, AppStateSetter) {

// do something with current , Start , and End

}

你可以test it on the Babel compiler:

这段代码:

const object = {
  current: {
    selectionStart: "prop 1",
    selectionEnd: "prop2"
  }
}

const { current: { selectionStart: Start, selectionEnd: End } } = object;

被转换成:

var object = {
  current: {
    selectionStart: "prop 1",
    selectionEnd: "prop2"
  }
};

var _object$current = object.current,
    Start = _object$current.selectionStart,
    End = _object$current.selectionEnd;

如您所见,current 变量未创建。

【讨论】:

  • 需要记住的一点,最佳做法是散布剩余的道具。所以如果你使用...rest(名字可以是任何东西)。您可以通过rest.current 访问当前
  • @Neil rest 不会有 current Babel
  • 如果在最后一个属性selectionEnd 之后添加...rest。然后这将是剩余的对象道具。我没有注意到第二级解构。
【解决方案2】:

我认为您面临的问题发生在当前为 undefined 时。

您可以尝试使用默认值进行破坏。

function ({ current: { selectionStart: Start, selectionEnd: End } = {} }, AppStateSetter) {
  // do something with Start and End
}

如果您认为还需要访问 current,请尝试在函数内部进行解构。

function ({ current = {}}, AppStateSetter) {
  const { selectionStart: Start, selectionEnd: End } = current
  // do something with current, Start and End
}

【讨论】:

    【解决方案3】:

    您可以在单个语句中解构并分配默认值。

    function someFunction({
            current: {
              selectionStart: Start,
              selectionEnd: End
            } = {},
            current = {}
          },
          AppStateSetter) {
          // now you can use the let variables Start, End and current,
          // with current's default value set to empty object
          }
    

    如果您不想为当前分配默认值,但仍想使用该变量,您可以只写属性的名称而不进行分配。当 someFunction 被空对象调用时,如果你没有给 current 赋值默认值,它将是未定义的。

        function someFunction1({
            current: {
              selectionStart: Start,
              selectionEnd: End
            } = {},
            current
          },
          AppStateSetter) {
          // now you can use the let variables Start, End and current
          // if empty object is passed, current will be undefined
        }
    

    JsFiddle sn-p:Nested object destructuring with and without default values

    【讨论】:

      猜你喜欢
      • 2019-06-15
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      相关资源
      最近更新 更多