Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES2015 deconstructing into an object [duplicate]

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

like image 724
Geraint Avatar asked Feb 02 '16 15:02

Geraint


1 Answers

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.

like image 181
ssube Avatar answered Oct 17 '22 18:10

ssube