Reputation: 6365
r = {
name:'Bart',
location:'Springfield'
}
for(var a in r) {
if (r.hasOwnProperty(a)) {
console.log(a);
const {a} = r[a]; // Here's where it's failing.
//I'm trying to do the equivalent of const{name} = r[a];
}
}
console.log(name) //Expecting output `Bart`
In my attempt to destructure an object, I've attempted what's above. However, this gives me 'Uncaught ReferenceError: Cannot access 'a' before initialization`
Do you see any way using which this could be solved?
Upvotes: 0
Views: 23093
Reputation: 5671
On this line
const {a} = r[a];
You are trying to define a new variable a
, which depends on using a
to access a property of r
.
Also, const { a }
means you are trying to access the property a
of r[a]. This can only work if r[a]
returns an object which also has it's own keys to destructure like so:
r = {
name: { a: 'Bart' },
location: { a: 'Springfield' }
}
In your code r[a]
will return the values, which are both strings. This means they don't have a property a
that you can destructure.
In which case, I assume you meant to just assign it to a variable, instead of destructuring
To avoid the error, try to avoid naming conflicts, perhaps by using more readable variable names and skip the destructuring like so:
for(var key in r) {
if (r.hasOwnProperty(key)) {
console.log(key);
const a = r[key];
}
}
Upvotes: 5
Reputation: 382
r = {
name:'Bart',
location:'Springfield'
}
r.name
contains 'Bari'
(string type) value not any Object value. So distructuring causes problem in your statement const {a} = r[a]
as r[a]
isn't an object. And remember const and let are always scope bound.
A possible workaround would be as follows
var r = {
name:'Bart',
location:'Springfield'
}
for(var a in r) {
if (r.hasOwnProperty(a)) {
globalThis[a] = r[a];
}
}
console.log(name)
Upvotes: 0