EN
JavaScript - access object property within the object
1 answers
0 points
How can I access the property of object within object?
I have the following object:
xxxxxxxxxx
1
var user = {
2
id: 1,
3
username: 'Mark',
4
country: 'USA',
5
place_of_residence: country,
6
};
I wanted to set place_of_residence
to country
value but it didn't work. I also tried using this.country
unsuccessfully.
1 answer
0 points
1. Using getter (ES6+)
Since ES6 you can use get
syntax to bind object property to a function that will be called when you try to access the property.
xxxxxxxxxx
1
var user = {
2
id: 1,
3
username: 'Mark',
4
country: 'USA',
5
get place_of_residence() {
6
return user.country;
7
},
8
};
9
10
console.log(user['place_of_residence']); // USA
2. Alternative solution
You can refer to the object property after the object is created.
xxxxxxxxxx
1
var user = {
2
id: 1,
3
username: 'Mark',
4
country: 'USA',
5
};
6
7
user['place_of_residence'] = user['country'];
8
9
console.log(JSON.stringify(user, null, 4));
Note:
In both cases you can alternativelu use dot property accessor like:
user.place_of_residence = user.country
References
0 commentsShow commentsAdd comment