object - How to interpret the [which]: part for the JavaScript expression ( { [which]: o[which] } = bar() ); -
i have encountered following code online:
function bar() { return { x: 4, y: 5, z: 6 }; } var = "x", o = {}; ( { [which]: o[which] } = bar() ); console.log( o.x );
i understand code example of "destructuring syntax" introduced in es6.
i understand o[which]
searching key named which
in object o
, if found, return value which
key.
but i'm not sure how [which]:
part of expression works.
in destructuring syntax, when see from : to
, means value of property identified from
taken thing being destructured , assigned variable or property identified to
. looking @ line:
( { [which]: o[which] } = bar() );
...we see value of property identified [which]
retrieved object returned bar
, assigned property identified o[which]
. since [which]
used rather which
, it's value of which
variable determines name of property taken bar
's returned object, when use brackets syntax when retrieving or setting value of property on object.
the non-destructuring version this:
const tmp = bar(); o[which] = tmp[which];
Comments
Post a Comment