考虑到一个对象:
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
如何删除财产 regex 以完成下一个 myObject?
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI"
};
考虑到一个对象:
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
如何删除财产 regex 以完成下一个 myObject?
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI"
};
当前回答
丹的说法是“删除”是非常缓慢的,他发布的参考标志是怀疑的,所以我自己在Chrome 59中进行了测试。
var iterationsTotal = 10000000; // 10 million
var o;
var t1 = Date.now(),t2;
for (let i=0; i<iterationsTotal; i++) {
o = {a:1,b:2,c:3,d:4,e:5};
delete o.a; delete o.b; delete o.c; delete o.d; delete o.e;
}
console.log ((t2=Date.now())-t1); // 6135
for (let i=0; i<iterationsTotal; i++) {
o = {a:1,b:2,c:3,d:4,e:5};
o.a = o.b = o.c = o.d = o.e = undefined;
}
console.log (Date.now()-t2); // 205
请注意,我故意在一个旋转周期内进行了多个“删除”操作,以尽量减少其他操作所造成的效果。
其他回答
@johnstock,我们也可以使用JavaScript的原型化概念,将方法添加到对象中,以删除在呼叫对象中可用的任何过渡密钥。
上面的答案值得欣赏。
var myObject = {“ircEvent”:“PRIVMSG”,“方法”:“newURI”,“regex”:“^http://.*” }; // 1st 和直接方式删除 myObject.regex; // 删除 myObject[“regex”] console.log(myObject); // { ircEvent:‘PRIVMSG’,方法:‘newURI’ } // 2 方式 - 使用 JavaScript 的原型概念 Object.prototype.removeFromObjectByKey = 函数(关键) { // 如果有,删除它并删除它
有几种方法可以从物体中删除属性:
1) 使用点属性附件移除(可变)
2. 使用方形布拉克特属性配件移除(可转换)
const myObject = { “ircEvent”: “PRIVMSG”, “method”: “newURI”, “regex”: “^http://.*”, }; delete myObject[‘regex’]; console.log(myObject); // or const name = ‘ircEvent’; delete myObject[name]; console.log(myObject);
3) 替代选项,但没有改变原始对象,使用对象破坏和休息合成(不变)
const myObject = { “ircEvent”: “PRIVMSG”, “method”: “newURI”, “regex”: “^http://.*”, }; const { regex,...myObjectRest} = myObject; console.log(myObjectRest);
一个没有财产的物体的克隆:
例如:
let object = { a: 1, b: 2, c: 3 };
我们必须删除A。
有一个明确的 prop 密钥: const { a,...rest } = 对象; 对象 = 休息; 有一个变量的 prop 密钥: const propKey = 'a'; const { [propKey]: propValue,...rest } = 对象; 对象 = 休息; A cool arrow 函数 <unk>: const removeProperty = (propKey, { [propKey]: propValue,...rest }) => 休息; 对象 = removeProperty('a', 对象); 多种属性 const removeProperties = (object,...keys)
使用
object = removeProperties(object, 'a', 'b') // result => { c: 3 }
或
const propsToRemove = ['a', 'b']
object = removeProperties(object, ...propsToRemove) // result => { c: 3 }
另一个解决方案,使用 Array#reduce。
(六)
const myObject = { ircEvent: 'PRIVMSG',方法: 'newURI', regex: '^http://.*', }; const myNewObject = Object.keys(myObject).reduce((obj, key) => { key!=='regex'? obj[key] = myObject[key] : null; return obj; }, {}); console.log(myNewObject);
删除对象的两种方式
使用为... 在函数中删除用户(键) { const newUsers = {}; for (const uid in users) { if (uid!== key) { newUsers[uid] = users[uid]; } return newUsers }
或
delete users[key]