Alexandr Lazarev
Alexandr Lazarev

Reputation: 12882

Destructuring assignment. Assign object and it's children in two different variables

There is a nested object:

var a = {
  b: {
   c: 'some value'
  }
}

Is there a way to make a destructing assignment to get following two variables with only one statement?

var c = 'some value';
var b = {c : {'some value'}}

Upvotes: 2

Views: 338

Answers (2)

Dan Prince
Dan Prince

Reputation: 29989

Just destructure the two parts separately.

var { b, b: { c } } = a;

Which compiles to the following code with Babel.

var _a = a;
var b = _a.b;
var c = _a.b.c;

Upvotes: 4

guest271314
guest271314

Reputation: 1

Try

var a = {
  b: {
   c: 'some value'
  }
}

var [c, b] = [a.b.c, a.b]

console.log(c, b)

Upvotes: 2

Related Questions