Rah*_*dhi 3 javascript object destructuring ecmascript-6
是否可以将某个对象的某些键拆包到新对象?
比方说,我想按键(3个拷贝a,b,c从)test对象到一个新的对象(abc)。下面提到的代码将起作用。
const test = {a:1, b:2, c:3, d:4, e:5 };
const {a, b, c} = test;
const abc = { a, b, c, f: 6};
Run Code Online (Sandbox Code Playgroud)
有什么方法可以在一个语句中完成?
还有另一种方法。
const test = {a:1, b:2, c:3, d:4, e:5 };
const abc = { ...test, f: 6};
Run Code Online (Sandbox Code Playgroud)
但是,使用这种方法,我后来不得不删除不需要的键(d,e在我的情况)。
(最佳情况解决方案:如果我们不必跟踪不需要的密钥。可以有n个不需要的密钥。)
您可以使用对象其余部分来破坏初始对象:
const test = {a:1, b:2, c:3, d:4, e:5 };
const {d, e, ...abc} = { ...test, f: 6};
console.log(abc);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
639 次 |
| 最近记录: |