我有一个类似下面的对象:
var doc = {
local: {
username: 'admin',
status: true,
password: '$2a$08$81Kq7/59ZASHl5k9n5cNvOUSl/HYgpLKZjs66P/OJV8vw.nHW60Ta',
lastname: 'admin',
firstname: 'admin',
email: '[email protected]',
datetime_modified: 'TueAug30201623: 10: 56GMT+0530(IST)',
datetime_created: 'MonAug29201622: 34: 12GMT+0530(IST)'
},
roles: [
'ADMIN',
'HR'
],
GridOrder: [
{
_id: '57e507fce94094be085425c9',
domainName: 'items'
}
],
_id: '57c46b0c12907af910167ff5',
__v: 9
}
现在,我想从“doc”中删除属性“GridOrder”。
我尝试使用“删除”,如下所示:
delete doc.GridOrder
也像下面这样:
delete doc['GridOrder']
但是什么也没发生。我也没有任何错误。
如何从“文档”中删除“GridOrder”。有任何想法吗?
最佳答案
使对象属性可配置
使用上述代码时,您的最小示例将按预期工作。
根据您的评论,GridOrder
实际上是使用Object.defineProperty()定义的,默认情况下,它会创建不可配置(读取:不可删除)属性。
定义属性configurable: true
时,只需将Object.defineProperty
传递给GridOrder
即可。
var doc = {
local: {
username: 'admin',
status: true,
password: '$2a$08$81Kq7/59ZASHl5k9n5cNvOUSl/HYgpLKZjs66P/OJV8vw.nHW60Ta',
lastname: 'admin',
firstname: 'admin',
email: '[email protected]',
datetime_modified: 'TueAug30201623: 10: 56GMT+0530(IST)',
datetime_created: 'MonAug29201622: 34: 12GMT+0530(IST)'
},
roles: [
'ADMIN',
'HR'
],
_id: '57c46b0c12907af910167ff5',
__v: 9
}
// Objects defined this way cannot be deleted unless `configurable` is set to `true`
Object.defineProperty(
doc,
'GridOrder',
{
configurable: true, // Defaults to `false`
value: [
{
_id: '57e507fce94094be085425c9',
domainName: 'items'
}
]
}
);
console.log('doc.GridOrder: ', doc.GridOrder);
console.log('delete doc.GridOrder: ', delete doc.GridOrder);
console.log('doc.GridOrder: ', doc.GridOrder);
警告
Advanced objects in JavaScript
如果您无权使用
defineProperty
创建GridOrder
的脚本,则以后将无法对其进行修改或删除。例如,这将失败:
/*
* Imagine this is provided by some third-party library that you're unable to edit
*/
var doc = {};
// Objects defined this way cannot be modified or deleted because `configurable` defaults to `false`.
Object.defineProperty(
doc,
'GridOrder',
{
value: [
{
_id: '57e507fce94094be085425c9',
domainName: 'items'
}
]
}
);
/*
* Within your script…
*/
console.log('doc.GridOrder: ', doc.GridOrder);
console.log('delete doc.GridOrder: ', delete doc.GridOrder);
console.log('doc.GridOrder: ', doc.GridOrder);
// …attempts to redefine non-configurable properties will fail
Object.defineProperty(
doc,
'GridOrder',
{
configurable: true
}
);
console.log('This will never be seen because an Error has been thrown above.');