Nicholas Hamilton
Nicholas Hamilton

Reputation: 10506

Javascript destructuring and assignment into new object

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}; // <---- 
}

Upvotes: 3

Views: 2127

Answers (2)

H4M5TER
H4M5TER

Reputation: 1

I think what you need is to filter the object by key without middle variables.

Here is my solutions:

let x = {a:1,b:2,c:3}
let y = {}
;({a: y.a, b: y.b} = x)
let filterObjectByKeys = (object, keys) => Object.fromEntries(keys.map(k => [k, object[k]]))
let x = {a:1,b:2,c:3}
let y = filterObjectByKeys(x, ['a', 'b'])

Reference:

  1. Assign value to new object via destructuring
  2. Filter object properties by key in ES6

Upvotes: 0

Ilya Kushlianski
Ilya Kushlianski

Reputation: 968

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 :)

Upvotes: 1

Related Questions