7

I am trying to deconstruct an object and apply the variables taken out into it's own object.

e.g. Object beforeTest contains a, b, c, d

I want to take { a, b } out and add it to afterTest object.

Something like...

let afterTest = { a, b } = beforeTest

The following works but isn't very pretty when you have many variables.

let { a, b } = beforeTest;
let afterTest = Object.assign({}, a, b); //EDIT: This doesn't actually do what I intended, see comment on my question

Anyone know of a nicer way to write this?

Thanks

Geraint
  • 2,974
  • 2
  • 21
  • 38
  • `Object.assign({}, a b)` isn't valid. Do you want `afterTest` to contain the properties of `a` and `b` or contain properties `a` and `b` with the same values as `beforeTest`? – ssube Feb 02 '16 at 15:49
  • Yeah, just been messing around and realise it doesn't achieve what I want. The latter of what you said, basically to create a new object with specified key/value pairs. – Geraint Feb 02 '16 at 15:52
  • Unfortunately, you will have to repeat variable declaration as well as object creation: `let { a, b } = beforeTest; let afterTest = {... {a, b}};` – dfsq Feb 02 '16 at 16:23

1 Answers1

2

Destructuring and object shorthand are best friends here.

To pick a few properties from an object and create a new object with that subset, you can simply do:

let {a, b} = beforeTest;
let afterTest = {a, b};

It doesn't make much sense to provide a one-line syntax for this, since the current syntax expands to multiple sources/sinks quite easily:

let {a1, b1} = beforeTest;
let {a2, b2} = midTest;
let aN = {a1, a2}, bN = {b1, b2};

You can get this working in one line if your source(s) do not have duplicate properties (i.e., only one of source 1 and 2 have field a), using map (pluck) and reduce:

let beforeTest = {a: 1, b: 2, c: 3};
let midTest = {d: 4, e: 5, f: 6};

let fields = ['a', 'c', 'd'];
let afterTest = Object.assign.apply({}, [beforeTest, midTest].map(obj => {
  return Object.keys(obj).filter(key => fields.includes(key)).reduce((p, key) => (p[key] = obj[key], p), {});
}));

console.log(afterTest);

I don't think that last method is worth the trouble, since it's pretty opaque as to where the data is coming from.

ssube
  • 41,733
  • 6
  • 90
  • 131