解构嵌套对象:如何获取父项及其子项的值?

Destructuring nested objects: How to get parent and its children values?

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

在这里,嵌套解构按预期使用 StartEnd 变量工作,但我还需要 current.

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

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

如何使用解构得到它?

第一个解构仅创建 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 变量未创建。

我认为您遇到的问题发生在电流为 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
}

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

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
      }

如果你不想给current赋默认值,但又想使用那个变量,你可以只写属性的名字,不赋值。当使用空对象调用 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 片段:Nested object destructuring with and without default values