javascript - How to delete from JSON Object using dynamic path using JQuery or Javascript
问题描述
I have a JSON Object "person" and i need to delete a key "age" which should be passed as a parameter to a function as the example given below. Inside the function the statement to delete the key is added as delete person+key;
but its not working. Please suggest the way to delete the key in the below manner, as i have to delete the keys dynamically on the "p" element click.
<!DOCTYPE html>
<html>
<head>
<script>
var person = {
firstname: "John",
lastname: "Doe",
age: 50,
eyecolor: "blue"
};
function funToDelete(key){
delete person+key;
document.getElementById("demo").innerHTML =
person.firstname + " is " + person.age + " years old.";
}
</script>
</head>
<body>
<p id="demo"></p>
<p onclick="funToDelete('.age')">Click me</p>
</body>
</html>
解决方案
使用delete
带有方括号表示法的运算符:
const person = {
firstname: "John",
lastname: "Doe",
age: 50,
eyecolor: "blue"
};
const key = 'age';
delete person[key];
console.log(person);
推荐阅读
- r - R markdown 代码显示我不想要的输出,我该如何删除它?
- reactjs - 根据当前 URL 更改链接的 className,React
- javascript - 在 Acrobat Pro 中使用 Javascript 更改日期格式
- c - c程序中使用指针的函数和数组
- c++ - QDate 从/到字符串的转换不一致(世纪问题)
- r - 未使用的参数(family = 二项式)
- android - Android - 导航后观察不起作用
- python - 如何确定动画 GIF 帧中透明像素的数量?
- android - 无法在 React Native 的 android 模拟器中安装应用程序
- django-rest-framework - Django Rest Framework 从数据库中获取最后一个元素