我们有多种方法来删除对象属性。
箭头函数:我们还可以使用箭头函数从对象中删除属性,这是一种简单的一行解决方案。
const obj = {
'first': 'one',
'second': 'two',
'third': 'three'
}
const fn = (key, { [key]: deletedKey, ...others }) => others;
console.log(fn('first', obj))
Reduce方法:我们可以使用reduce方法在JavaScript中从原始对象中删除特定属性。
const obj = {
'first': 'one',
'second': 'two',
'third': 'three'
}
const exceptSecond = Object.keys(obj).reduce((acc, key) => {
if (key !== 'second') {
acc[key] = obj[key]
}
return acc
}, {})
console.log(exceptSecond)
删除:这是简单易行的删除方式。
delete obj.first;
// Or
delete obj['first'];
使用 "loadash" 库中的 unset、omit、pick 方法:
import { unset } from 'lodash'
const obj = {
'first': 'one',
'second': 'two',
'third': 'three'
}
unset(obj, 'third')
console.log(obj)
import { omit } from 'lodash'
const obj1 = {
'first': 'one',
'second': 'two',
'third': 'three'
}
omit(obj1, [ 'first', 'second' ])
console.log(obj1)
反射删除属性: 这是ES6中引入的新内置对象。现在可以通过从该反射对象调用已删除属性()函数来删除对象属性。
此函数相当于我们在第一种方法中使用的delete运算符。
const someObject = {
'first': 'one',
'second': 'two',
'third': 'three'
}
Reflect.deleteProperty(someObject, 'second')
console.log(someObject) // { 'first': 'one', 'third': 'three' }
var obj = { helloText: "Hello World!" }; var foo = obj; delete obj;
注意:对象并没有被删除,请检查obj
。 正确的用法是:delete obj.helloText
然后再检查foo
,此时foo
就变成了一个空对象。 - Umair Ahmeddelete`在Javascript中并不是用于删除对象的。`delete`用于移除对象的键。在您的情况下 `var obj = { helloText: "Hello World!" }; var foo = obj; delete obj;`, 对象并没有被删除。请检查`obj`。然后运行`delete obj.helloText`,您会看到`foo`现在指向一个空对象。
- PacerierObject.defineProperty()
/Object.defineProperties()
定义属性,任何未显式设置为configurable: true
的属性都无法被删除。嘿,我曾经为此苦恼了一段时间。 - Phil Tune