从对象中删除没有变异的值 [英] Remove value from object without mutation

查看:115
本文介绍了从对象中删除没有变异的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想做类似的事情:

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

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

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

有吗这样的东西用于删除值? ES6非常受欢迎。

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

非常感谢!

推荐答案

更新:



您可以使用棘手的解构分配

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
}

您也可以使用 省略函数来自 lodash 实用程序库

Alternatively you could use omit function from lodash utility library:

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

它作为 lodash 包,或作为独立的 lodash.omit 包。

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

这篇关于从对象中删除没有变异的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆