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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With