ES2015 is deconstructing into an object

I am trying to deconstruct an object and apply variables taken into its own object.

eg. BeforeTest object contains a, b, c, d

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

Sort of...

let afterTest = { a, b } = beforeTest

The following works, but not very beautiful, 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

Does anyone know of a more convenient way to write this?

thanks

+4
source share
1 answer

Restructuring and downsizing are the best friends here.

To select several properties of an object and create a new object with this subset, you can simply do:

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

, /:

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

, (.. 1 2 a), (pluck) :

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

, , , .

+2

Source: https://habr.com/ru/post/1627046/


All Articles