Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...