Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The function below receives an object that has a property current, which is also an object, and it has selectionStart and selectionEnd properties.

Here, nested destructuring works as expected with Start and End variables, But I also need the value for current.

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

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

How do I get it using destructuring?

like image 373
soufiane yakoubi Avatar asked Feb 08 '19 11:02

soufiane yakoubi


1 Answers

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.

like image 101
adiga Avatar answered Oct 26 '22 19:10

adiga