首页 > 解决方案 > 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>

标签: javascriptjqueryhtmlcssjson

解决方案


使用delete带有方括号表示法的运算符:

const person = {
  firstname: "John",
  lastname: "Doe",
  age: 50,
  eyecolor: "blue"
};
const key = 'age';

delete person[key];

console.log(person);


推荐阅读