0

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?

Lazar Nikolic
  • 4,261
  • 1
  • 22
  • 46
Gorakh Nath
  • 9,140
  • 15
  • 46
  • 68
  • Related: [How do I remove a property from a JavaScript object?](https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object) Also, [JavaScript property access: dot notation vs. brackets?](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – Jonathan Lonowski Sep 20 '18 at 06:38

1 Answers1

3

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)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320