JavaScript 如何从对象中删除与给定键相对应的键值对
在JavaScript中,对象以 键-值对 的形式存储数据,其中键可以是对象的任何属性。在本文中,让我们看看如何从对象中删除与给定键相对应的 键-值对 。
- 使用 delete 操作符
- 使用 filter() 方法
使用delete 操作符
当只需要删除一个键时,我们可以直接使用delete操作符,并在对象中指定键。
语法:
delete(object_name.key_name);
/* or */
delete(object_name[key_name]);
示例 1: 本示例描述了从对象中删除键值对的上述方法。
var myObj = {
Name: "Raghav",
Age: 30,
Sex: "Male",
Work: "Web Developer",
YearsOfExperience: 6,
Organisation: "GeeksforGeeks",
Address: "address--address some value"
};
console.log("After removal: ");
// Deleting address key
delete (myObj.Address); // Or delete(myObj[Address]);
console.log(myObj);
输出:
"After removal: "
[object Object] {
Age: 30,
Name: "Raghav",
Organisation: "GeeksforGeeks",
Sex: "Male",
Work: "Web Developer",
YearsOfExperience: 6
}
当需要移除 多个键 时,可以将这些键存储在一个 数组 中,并将其传递给使用循环来删除数组中所需键的函数。
语法:
function function_name(object_name, array_of_keys) {
{ Iterate through the array using loop. }
return object_name;
}
示例2: 该示例使用循环从对象中删除一个键值对。
// Function to delete the keys given in the array
function DeleteKeys(myObj, array) {
for (let index = 0; index < array.length; index++) {
delete myObj[array[index]];
}
return myObj;
}
// Declaring the object
var myObj = {
Name: "Raghav",
Age: 30,
Sex: "Male",
Work: "Web Developer",
YearsOfExperience: 6,
Organisation: "Geeks For Geeks",
Address: "address--address some value"
};
// Adding the keys to be deleted in the array
var array =
["Work", "Address", "Organisation", "YearsOfExperience"];
var finalobj = DeleteKeys(myObj, array);
console.log("After removal: ");
console.log(finalobj);
输出:
"After removal: "
[object Object] {
Age: 30,
Name: "Raghav",
Sex: "Male"
}
使用filter()方法
JavaScript Array filter()方法用于从给定数组中创建一个新数组,该数组只包含满足参数条件的元素。
示例: 在这个示例中,我们将看到使用filter()方法来删除键值对。
let obj = { name: "Joey", age: "30", gender: "Male" };
let newObj = Object.keys(obj)
.filter(key => key != "name")
.reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {});
console.log(newObj)
输出
{ age: '30', gender: 'Male' }