繁体   English   中英

如何使用ES6扩展运算符和rest运算符从数组或对象中删除特定元素

[英]How to remove specific element from a array or object using ES6 spread operators and rest operators

我想做这样的事情。 有像

obj = { a: "xxx", b: "xxx", c: "xxx", d: "xxx", e: "xxx", f: "xxx" }

我想删除属性cd的值,并将它们放在数组中,如arr = ["xxx" , "xxx"] 然后我想将此数组添加到obj对象中

obj = { a: "xxx", b: "xxx",  c: ["xxx", "xxx"], e: "xxx", f: "xxx" }

所以有没有办法使用ES6传播和休息操作员

如果我必须删除n个值的值(未知值可以是1或2或3 ..),然后将它们放入数组,该如何处理(如上所述)

您可以使用解构和临时const来实现。

 const obj = {a:"xxx" , b:"xxx", c:"xxx" , d:"xxx" , e:"xxx", f:"xxx"} const { c, d, ...rest} = obj; // pick props you want to remove and keep rest // create a new object by spreading `rest` and adding new property console.log({...rest, c: [c, d]}); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM