ES2015解构为一个对象 [英] ES2015 deconstructing into an object

查看:183
本文介绍了ES2015解构为一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解构一个对象并将取出的变量应用到它自己的对象中。

I am trying to deconstruct an object and apply the variables taken out into it's own object.

例如。 Object beforeTest包含a,b,c,d

e.g. Object beforeTest contains a, b, c, d

我想将{a,b}取出并添加到afterTest对象。

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

类似......

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?

谢谢

推荐答案

解构和对象简写是这里最好的朋友。

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

如果你的来源没有重复的属性,你可以在一行中工作(即,使用map(pluck)和reduce:

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.

这篇关于ES2015解构为一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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