I have a block of code:
const {address, cityDistrict, city, country} = data;
const obj = {
location: {address, cityDistrict, city, country}
};
But can I write this one shorted? I tried this one, but it's wrong:
const obj = {
location: {address, cityDistrict, city, country} = data
};
Is it possible?
This will not work using the es2015 preset, but will work using es2016.
Trying this in https://babeljs.io/repl illustrates this.
Updated
The answer from CodingIntrigue shows why this one does not work.
I also think what you want is currently not achievable with a destructuring one-liner. You'd better stick to your first intent unless you really don't want to have some variables assignments, and in such case you'd likely use an IIFE to filter keys.
As zeroflagl said, you can do it using spread properties if you use ES proposal stage 3.
const data = {
address: 'address',
cityDistrict: 'district',
city: 'city',
country: 'country'
}
const { address, cityDistrict, city, country } = data;
const obj = {
location: {...data}
};
console.log(obj)
/* logs Object {
"location": Object {
"address": "address",
"city": "city",
"cityDistrict": "district",
"country": "country"
}
}
*/