简体   繁体   中英

Function to delete a property from object in javascript

I want to write a function which will return true if property of the object is deleted and for others it should return me false.The function accepts two parameters, object and the property name.This can be more clear withe the below code:-

 var removeObjectProp = function(obj, propName) { if (obj.hasOwnProperty(propName)) { return delete obj.propName; } return false; } var emp = { name: 'jack', age: 12 }; console.log(removeObjectProp(emp, 'name')); console.log(emp) 

output:

    True
    {name: "jack", age: 12}
    age:12
    name:"jack"
    __proto__:
    Object
   }

So again I am getting the same object.If I modify the function:-

 var removeObjectProp = function(obj, propName){
         return delete obj.propName;
    } 

and call the

console.log(removeObjectProp (emp,'salary'));

Always it is returning true. How can i write the function to delete the property of an object passed as parameter?

In order to delete a property, if the property name is a string you have in a variable, you need to use bracket notation to delete the property:

return delete obj[propName];

You would use

delete obj.propName;

only when propName was the literal name of the property, eg with

{ name: 'jack', propName: 'foo' }

 var removeObjectProp = function(obj, propName) { if (obj.hasOwnProperty(propName)) { return delete obj[propName]; } return false; } var emp = { name: 'jack', age: 12 }; console.log(removeObjectProp(emp, 'name')); console.log(removeObjectProp(emp, 'propThatDoesNotExist')); console.log(emp) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM