从对象中删除值而不进行变异

时间:2021-09-16 18:02:54

What's a good and short way to remove a value from an object at a specific key without mutating the original object?

在不改变原始对象的情况下从特定键的对象中删除值的好方法和简短方法是什么?

I'd like to do something like:

我想做的事情如下:

let o = {firstname: 'Jane', lastname: 'Doe'};
let o2 = doSomething(o, 'lastname');
console.log(o.lastname); // 'Doe'
console.log(o2.lastname); // undefined

I know there are a lot of immutability libraries for such tasks, but I'd like to get away without a library. But to do this, a requirement would be to have an easy and short way that can be used throughout the code, without abstracting the method away as a utility function.

我知道这些任务有很多不变的库,但我想在没有库的情况下逃脱。但要做到这一点,一个要求是有一个简单而简短的方法可以在整个代码中使用,而不会将方法作为效用函数抽象出来。

E.g. for adding a value I do the following:

例如。要添加值,我执行以下操作:

let o2 = {...o1, age: 31};

让o2 = {... o1,年龄:31};

This is quite short, easy to remember and doesn't need a utility function.

这很简单,易于记忆,不需要实用功能。

Is there something like this for removing a value? ES6 is very welcome.

是否有类似的东西去除值? ES6非常受欢迎。

Thank you very much!

非常感谢你!

4 个解决方案

#1


120  

Update:

You could remove a property from an object with a tricky Destructuring assignment:

您可以通过棘手的Destructuring赋值从对象中删除属性:

const doSomething = (obj, prop) => {
  let {[prop]: omit, ...res} = obj
  return res
}

Though, if property name you want to remove is static, then you could remove it with a simple one-liner:

但是,如果要删除的属性名称是静态的,那么您可以使用简单的单行删除它:

let {lastname, ...o2} = o

The easiest way is simply to Or you could clone your object before mutating it:

最简单的方法就是或者你可以在变异之前克隆你的对象:

const doSomething = (obj, prop) => {
  let res = Object.assign({}, obj)
  delete res[prop]
  return res
}

Alternatively you could use omit function from lodash utility library:

或者你可以使用lodash实用程序库中的省略函数:

let o2 = _.omit(o, 'lastname')

It's available as a part of lodash package, or as a standalone lodash.omit package.

它作为lodash包的一部分提供,或作为独立的lodash.omit包提供。

#2


3  

one line solution

一线解决方案

const removeKey = (key, {[key]: _, ...rest}) => rest;

#3


2  

As suggested in the comments above if you want to extend this to remove more than one item from your object I like to use filter. and reduce

正如上面的评论中所建议的,如果你想扩展它以从你的对象中删除多个项目,我想使用过滤器。并减少

eg

例如

    const o = {
      "firstname": "Jane",
      "lastname": "Doe",
      "middlename": "Kate",
      "age": 23,
      "_id": "599ad9f8ebe5183011f70835",
      "index": 0,
      "guid": "1dbb6a4e-f82d-4e32-bb4c-15ed783c70ca",
      "isActive": true,
      "balance": "$1,510.89",
      "picture": "http://placehold.it/32x32",
      "eyeColor": "green",
      "registered": "2014-08-17T09:21:18 -10:00",
      "tags": [
        "consequat",
        "ut",
        "qui",
        "nulla",
        "do",
        "sunt",
        "anim"
      ]
    };

    const removeItems = ['balance', 'picture', 'tags']
    console.log(formatObj(o, removeItems))

    function formatObj(obj, removeItems) {
      return {
        ...Object.keys(obj)
          .filter(item => !isInArray(item, removeItems))
          .reduce((newObj, item) => {
            return {
              ...newObj, [item]: obj[item]
            }
          }, {})
      }
    }

    function isInArray(value, array) {
      return array.indexOf(value) > -1;
    }

#4


0  

With ES7 object destructuring:

使用ES7对象解构:

const myObject = {
  a: 1,
  b: 2,
  c: 3
};
const { a, ...noA } = myObject;
console.log(noA); // => { b: 2, c: 3 }

#1


120  

Update:

You could remove a property from an object with a tricky Destructuring assignment:

您可以通过棘手的Destructuring赋值从对象中删除属性:

const doSomething = (obj, prop) => {
  let {[prop]: omit, ...res} = obj
  return res
}

Though, if property name you want to remove is static, then you could remove it with a simple one-liner:

但是,如果要删除的属性名称是静态的,那么您可以使用简单的单行删除它:

let {lastname, ...o2} = o

The easiest way is simply to Or you could clone your object before mutating it:

最简单的方法就是或者你可以在变异之前克隆你的对象:

const doSomething = (obj, prop) => {
  let res = Object.assign({}, obj)
  delete res[prop]
  return res
}

Alternatively you could use omit function from lodash utility library:

或者你可以使用lodash实用程序库中的省略函数:

let o2 = _.omit(o, 'lastname')

It's available as a part of lodash package, or as a standalone lodash.omit package.

它作为lodash包的一部分提供,或作为独立的lodash.omit包提供。

#2


3  

one line solution

一线解决方案

const removeKey = (key, {[key]: _, ...rest}) => rest;

#3


2  

As suggested in the comments above if you want to extend this to remove more than one item from your object I like to use filter. and reduce

正如上面的评论中所建议的,如果你想扩展它以从你的对象中删除多个项目,我想使用过滤器。并减少

eg

例如

    const o = {
      "firstname": "Jane",
      "lastname": "Doe",
      "middlename": "Kate",
      "age": 23,
      "_id": "599ad9f8ebe5183011f70835",
      "index": 0,
      "guid": "1dbb6a4e-f82d-4e32-bb4c-15ed783c70ca",
      "isActive": true,
      "balance": "$1,510.89",
      "picture": "http://placehold.it/32x32",
      "eyeColor": "green",
      "registered": "2014-08-17T09:21:18 -10:00",
      "tags": [
        "consequat",
        "ut",
        "qui",
        "nulla",
        "do",
        "sunt",
        "anim"
      ]
    };

    const removeItems = ['balance', 'picture', 'tags']
    console.log(formatObj(o, removeItems))

    function formatObj(obj, removeItems) {
      return {
        ...Object.keys(obj)
          .filter(item => !isInArray(item, removeItems))
          .reduce((newObj, item) => {
            return {
              ...newObj, [item]: obj[item]
            }
          }, {})
      }
    }

    function isInArray(value, array) {
      return array.indexOf(value) > -1;
    }

#4


0  

With ES7 object destructuring:

使用ES7对象解构:

const myObject = {
  a: 1,
  b: 2,
  c: 3
};
const { a, ...noA } = myObject;
console.log(noA); // => { b: 2, c: 3 }