【问题标题】:How to remove specific element from a array or object using ES6 spread operators and rest operators如何使用 ES6 扩展运算符和剩余运算符从数组或对象中删除特定元素
【发布时间】:2018-08-21 07:00:18
【问题描述】:

我想做这样的事情。 有类似的对象

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 ..)属性并将它们放入数组中,我已经解释过,该怎么做

【问题讨论】:

  • 欢迎来到 StackOverflow。请阅读此how to ask
  • 为什么 'f' 被添加到你的新 json obj 中?
  • @G_S 我在那里。由于格式不正确,刚刚换行。
  • 如果属性及其编号未知,则不能使用rest/spread语法。
  • ... is not an operator,并且对象休息/传播属性不是 ES6 的一部分。今年将与 ES9 一起推出。

标签: javascript reactjs ecmascript-6 spread-syntax


【解决方案1】:

您可以使用解构和临时常量来做到这一点。

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

【讨论】:

    猜你喜欢
    • 2019-02-21
    • 2019-10-27
    • 2019-01-15
    • 1970-01-01
    • 2017-05-14
    • 2020-05-08
    • 2017-03-17
    • 1970-01-01
    • 2018-05-13
    相关资源
    最近更新 更多