簡體   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