This actually does work (in Chrome at least, in Babel too if you wrap the assignment in parenthesis), but the two pieces of code are not equivalent.
The second piece of code simply assigns data
to the location
property and creates 4 new variables in scope called address
, cityDistrict
, etc.
For example:
const data = {
address: "Address",
cityDistrict: "District",
city: "City",
country: "Country"
}
const obj = {
location: ({address, cityDistrict, city, country} = data)
};
console.log(obj);
Looks like it logs the correct data, but what is actually printing is data
, not new object. So if we do something like this:
const obj = {
location: ({address, cityDistrict, city, country} = data)
};
data.address = "Test"
console.log(obj); // location.Address = Test
You'd get unexpected data. As a side effect of that, you'd also get 4 new variables in scope:
const obj = {
location: ({address, cityDistrict, city, country} = data)
};
console.log(address, cityDistrict, city, country); // All defined
What you really want to do is to use Object.assign
to create a new instance of an object:
const obj = {
location: Object.assign({}, data);
}