给定一个对象:
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"
};
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
obj = Object.fromEntries(
Object.entries(myObject).filter(function (m){
return m[0] != "regex"/*or whatever key to delete*/
}
))
console.log(obj)
您也可以使用Object.entries
将对象视为类似于a2d
数组,并像在普通数组中一样使用splice来删除元素,或者就像处理数组一样对对象进行过滤,然后将重构后的对象赋值回原始变量。
const object = {
prop1: 10,
prop2: 20,
prop3: 30,
"test prop": "This is test props"
}
console.log(object); // will print all 4 props
delete object.prop1;
delete object["test prop"];
console.log(object); // it will print only prop2 and prop3
删除对象的两种方式
using for ... in
function deleteUser(key) {
const newUsers = {};
for (const uid in users) {
if (uid !== key) {
newUsers[uid] = users[uid];
}
return newUsers
}
或者
delete users[key]
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*",
"regex1": "^http://.*",
"regex2": "^http://.*",
"regex3": "^http://.*",
"regex4": "^http://.*"
};
delete myObject.regex; // using delete object.property
// Or
delete myObject['regex1']; // using delete object['property']
const { regex2, regex3, regex4, ...newMyObject } = myObject;
console.log(newMyObject);
简短回答
var obj = {
data: 1,
anotherData: 'sample'
}
delete obj.data //this removes data from the obj
你现在剩下的是:
var obj = {
anotherData: 'sample'
}
在JavaScript中,有两种常见的方法可以从一个对象中删除属性。
第一种可变的方法是使用delete object.property
操作符。
第二种方法是不可变的,因为它不会修改原始对象,而是调用对象解构和展开语法:const {property, ...rest} = object
这是我的做法。
const obj = {
name: 'John',
age: 30,
gender: 'male'
};
delete obj.age;
console.log(obj); // { name: 'John', gender: 'male' }