Javascript destructuring and assignment into new object

Viewed 234

Lets say I have an object:

let x = {a:1,b:2,c:3}

Now I can destructure as follows:

let {a,b} = x;

Is it possible to assign, (in the same line as the destructuring) these into a new object, the equivalent of?:

let newObject = {a,b};

or (in pseudocode, I realise this doesn't work)

let newObject = {a,b} = x;

or would I be required to use something as lodash _.pickBy function?

let newObject = _.pickBy(x,['a','b'])

The reason I am asking is, I would like to do something like that for functions signatures:

let fun = ({a,b}) => {
    let args = {a,b}; // <---- 
}
1 Answers

It seems impossible, because, while looking the same, the destructuring assignment and object syntaxes are completely different things.

let a, b;
{a,b} = x  <-- {a,b} is not an object

If you try returning the result of destructuring assignment, it will still be returning x, the full object.

const result = {a,b} = x 
// `result` is the full object

or

const result = ({a,b} = x);
// `result` is the full object

Anyway, writing such one-liners could be extremely confusing to teammates. It would raise my eyebrows during a peer review anyways :)

Related