I have this variable:
var a = {b:1, c:2, d:'rawr', rawr:10};
I want to destructure these into the local scope so I do:
var {b, c, d} = a;
This works fine but I need to get rawr
out. I tried this:
var {b, c, d, [a.d]} = a;
But this gives me missing : after property id
so I tried:
So I then though to do a two step:
var {b, c, d} = a;
var {[d]} = a;
However this gives me SyntaxError: missing : after property id
. Is there anyway to do this in ES6?
Expected result is that:
var b = 1;
var c = 2;
var d = 'rawr';
var rawr = 10;
I have this variable:
var a = {b:1, c:2, d:'rawr', rawr:10};
I want to destructure these into the local scope so I do:
var {b, c, d} = a;
This works fine but I need to get rawr
out. I tried this:
var {b, c, d, [a.d]} = a;
But this gives me missing : after property id
so I tried:
So I then though to do a two step:
var {b, c, d} = a;
var {[d]} = a;
However this gives me SyntaxError: missing : after property id
. Is there anyway to do this in ES6?
Expected result is that:
var b = 1;
var c = 2;
var d = 'rawr';
var rawr = 10;
Share
Improve this question
edited May 5, 2016 at 0:49
timolawl
5,56415 silver badges29 bronze badges
asked May 5, 2016 at 0:21
NoitidartNoitidart
37.2k40 gold badges176 silver badges352 bronze badges
34
|
Show 29 more comments
4 Answers
Reset to default 15You can destructure it like this:
var {b, c, d, [d]: q} = a;
So then whatever was in a property with a name d
is assigned to q
.
UPD:
What you asked in the update is not possible.*
You need to give it a variable to assign to. You cannot use "computed" variable names1, as that would go against the rules of static scope resolution for identifiers. So you should do
var {b, c, d, [a.d]: rawr} = a;
to get the value of the a.d
-named property in the rawr
variable.
1: Well, you can use eval
or a with
statement in sloppy mode to do this, but both are despised exactly because of this.
When dealing with computed objects property destruction the value of the string literal needs to correspond with the key name you are referencing in your object: for example
// string literal
const getRawr = 'd'
const { [getRaw]: rawr } = {b:1, c:2, d:'rawr', rawr:10};
console.log(raw);
You could use Object.keys()
, Function.prototype.bind()
though caveat is that value of variable is within an array; have not yet determined how to return only variable.
var a = {
b: 1,
c: 2,
d: 'rawr',
rawr: 10
};
function de(val, key) {
var [val] = window[val] = [a[val]];
}
Object.keys(a).forEach(de.bind(this));
console.log(b, c, d, rawr);
jsfiddle https://jsfiddle.net/ravkgzjb/2/
rawr
)? – Felix Kling Commented May 5, 2016 at 0:40