i have an object coming from an API respone, looks like this:
{
// ...
customerName: 'Jake',
customerUserName: 'jak3',
customerEmail: '[email protected]',
// ...
}
and i want to declare a new object named apiUser
to use in my app which sould look like this:
{
name: 'Jake',
userName: 'jak3',
email: '[email protected]'
}
i know i can do that using Object.assign()
like this:
let apiUser = {};
Object.assign(apiUser, {
name: response.customerName || 'John Doe', // customerName may be an empty string
userName : response.customerUserName,
email: response.customerEmail
});
Finally the question is: Can i do that by object destructuring? I've already tried:
let apiUser = {};
{customerName: apiUser.name, customerUserName: apiUser.userName, customerEmail: apiUser.email} = response;
but throwed and SyntaxError: Unexpected token :
Is there any right syntax or should i stick with Object.assign()
? And please don't forget the "John Doe" condition.
It works as you'd expect:
According to the MDN documentation of Assignment without declaration:
Note: both Object.Assign and destructured assignment are by-and-large not available in Internet Explorer (Edge is a different story). Take that into consideration for your implementation.