Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do object restructuring in ES6?

Is there a way to do this in a single statement?

var {a:c, b} = {a:2, b:3}; // es6 destructuring
var d = {b, c} // es6 shorthand properties

I want to transform {a:2, b:3} to {b:3, c:2} in a single statement.

like image 251
kunalgolani Avatar asked Dec 19 '22 03:12

kunalgolani


2 Answers

Don't use destructuring and shorthand properties, just construct your literal like you want:

var input = {a:2, b:3};

var d = {b:input.b, c:input.a}; // single statement

Alternatively use an immediately invoked arrow function (IIAF):

var d = (({a:c, b}) => ({b, c}))(input);
like image 162
Bergi Avatar answered Dec 24 '22 03:12

Bergi


I want to transform {a:2, b:3} to {b:3, c:2} in a single statement.

You just need to swap the properties:

const {b, a:c} = {a:2, b:3}
b // 3
c // 2
like image 39
Bhojendra Rauniyar Avatar answered Dec 24 '22 01:12

Bhojendra Rauniyar