Destructuring nested objects: How to get parent and it's children values?

白昼怎懂夜的黑 提交于 2019-12-17 16:47:12

问题


In the below function, I get the textarea object with the property current .

Here, nested destructuring works with Start and End variables. But current variable doesn't work.

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

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

回答1:


The first destructuring creates only Start and End variables. If you want to create current as a variable, then you need to declare it again.

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

// do something with current , Start , and End

}

You can test it on the Babel compiler:

This code:

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

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

Gets trasnpiled to:

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

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

As you can see, current variable is not created.




回答2:


I think the issue you are facing happens when current is undefined.

You can try destructing with default value.

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

If you think you need to access current as well, try destructuring inside the function.

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



回答3:


You can destructure and assign the default value in a single statement.

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
      }

If you don't want to assign default value to current, but still want to use that variable, you can just write the name of the property with no assignment. When someFunction is called with empty object, if you don't assign a default value to current it will be undefined.

    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 snippet: Nested object destructuring with and without default values



来源:https://stackoverflow.com/questions/54591307/destructuring-nested-objects-how-to-get-parent-and-its-children-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!