Destructuring nested objects: How to get parent an

2019-02-23 01:36发布

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
}

2条回答
叼着烟拽天下
2楼-- · 2019-02-23 01:57

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
}
查看更多
▲ chillily
3楼-- · 2019-02-23 02:00

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.

查看更多
登录 后发表回答