Is there an easier way to map the properties of one object to another in ES6 / ES2015?

Let's say I have a foo object with properties a and b , but I want to transfer the values ​​of these properties to another bar object with properties x and y , where it bar.xgets the value foo.aand bar.ygets the value foo.b.

The first way that comes to mind to do with ES5 will be as follows:

var foo = { a: 5, b: 17 };
var bar = { x: foo.a, y: foo.b };

This is already quite brief, but in each case you need to refer to foo, in order to access its properties, it becomes noisy for a larger comparison of properties. Looking at the new destructuring functions in ES6, it seems that you can destroy nested objects in a flattened set of variables, but I have not found examples that indicate the ability to specify an object in which property values ​​will be destroyed instead. This function does not exist or I just did not find an example showing how this is done? If this is not possible, are there other smart tricks that can be done to achieve a similar result?

To be clear, I was hoping to do something in accordance with the examples below.

var foo = { a: 5, b: 17 };
var bar = { a: x, b: y } = foo;

(One-liner, ES 6), foo, . .

+4
1

let foo = {a: 5, b: 17, c: 10};
let {a,b,c} = foo;
let bar = {x: a, y: b, c};
console.log(bar);
// => {x:5, y:17, c:10}
+2

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


All Articles