Is there a more terse way to map properties of one object to another in ES6/ES2015?

会有一股神秘感。 提交于 2019-12-21 17:56:12

问题


Say I have an object foo with properties a and b but I want to transfer the values of these properties to another object bar with properties x and y where bar.x gets the value of foo.a and bar.y gets the value of foo.b.

The first way that comes to mind to accomplish this with ES5 would be like the following.

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

This is already pretty terse but having to reference foo in each case to access it's properties gets noisy for a larger property mapping. Looking in to the new destructuring features in ES6 it seems that it is possible to destructure nested objects into a flattened set of variables but I haven't found any examples which point out the ability to specify an object in which to destructure property values instead. Does this feature not exist or have I just not found the example that shows how this is done? If it is not possible are there any other clever tricks that can be done to achieve a similar result?

To be clear I was hoping to be able to do something along the lines of the example below.

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

This question is different from (One-liner to take some properties from object in ES 6) because I'm looking for a way to avoid writing foo and not the property list. In fact keeping the property list for explicit mapping is my goal.


回答1:


Destructuring assignment allows you to do this pretty easily

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}


来源:https://stackoverflow.com/questions/35471531/is-there-a-more-terse-way-to-map-properties-of-one-object-to-another-in-es6-es20

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!