ES6-解构分配-将某些属性从现有对象解压缩到新对象? [英] ES6 - Destructuring assignment - Unpack some properties from existing object to a new object?
本文介绍了ES6-解构分配-将某些属性从现有对象解压缩到新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将一个对象的某些键解压缩到一个新对象中?
Is it possible to unpack some of the keys of an object to a new object?
比方说,我要将3个键(a
,b
,c
)从test
对象复制到新对象(abc
).下面提到的代码将起作用.
Let's say, I want to copy 3 of the keys (a
, b
, c
) from test
object to a new object (abc
). Below mention code will work.
const test = {a:1, b:2, c:3, d:4, e:5 };
const {a, b, c} = test;
const abc = { a, b, c, f: 6};
有什么方法可以在一个语句中完成?
还有另一种方法.
const test = {a:1, b:2, c:3, d:4, e:5 };
const abc = { ...test, f: 6};
但是使用这种方法,以后我将不得不删除不需要的密钥(在我的情况下为d
,e
).
But with this approach, I would later have to delete the unwanted keys (d
, e
in my case).
(最佳方案:如果我们不必跟踪不需要的密钥.不需要的密钥可以有n个.)
(Best Case Solution: If we don't have to keep track of unwanted keys. There can be n number of unwanted keys.)
推荐答案
You can use object rest to destructure your initial object:
const test = {a:1, b:2, c:3, d:4, e:5 };
const {d, e, ...abc} = { ...test, f: 6};
console.log(abc);
这篇关于ES6-解构分配-将某些属性从现有对象解压缩到新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文