在ES6 / ES2015中,将一个对象的属性映射到另一个对象是否有更简单的方法? [英] Is there a more terse way to map properties of one object to another in ES6/ES2015?

查看:1712
本文介绍了在ES6 / ES2015中,将一个对象的属性映射到另一个对象是否有更简单的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个对象 foo ,属性 a b ,但是我想将这些属性的值传输到另一个对象 bar ,其中 x y ,其中 bar.x 获取 foo.a bar.y 获取 foo.b 的值。



使用ES5完成此任务的第一个方法如下:

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

这已经很简洁了,但不得不引用 foo 在每种情况下,访问它的属性获取较大的属性映射嘈杂。考虑到ES6中的新的破坏功能,似乎有可能将嵌套对象重构为一系列变量,但是我还没有找到任何可以指定在其中重建属性值的对象的例子。这个功能是不存在还是没有找到显示如何完成的例子?如果不可能有任何其他聪明的技巧可以做到以达到类似的结果?



要清楚,我希望能够做一些沿着

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

这个问题与(单行从ES 6中的对象中获取一些属性),因为我正在寻找一种方法来避免写 foo 而不是属性列表。实际上保持属性列表是显式映射的目标。

解决方案

解析方法允许你很容易地做到这一点>

  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}


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.

解决方案

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}

这篇关于在ES6 / ES2015中,将一个对象的属性映射到另一个对象是否有更简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆