简体   繁体   中英

Remove property from object

If object obj has a property prop , the function removes the property from the object and returns true, in all other cases returns false.

Right now, it's returning the correct value, but the test that shows if the property is removed is failing.

Would it be because I'm trying to delete from a newly made array from object, instead of the original object itself?

function removeProperty(obj, prop) {

  let newObj = Object.keys(obj);

  if(newObj.includes(prop)){

     delete newObj.prop

     return true

    }


  return false

}

It looks like the desire is to mutate the obj . In this case, you're creating a new object entirely which the caller does not have access to. You should change your code to delete from obj

if (obj.hasOwnProperty(prop)) {
  delete obj[prop];
  return true;
}
return false;

Here is the documentation for hasOwnProperty Documentation

Currently, you are trying to delete from your array of keys, not your object, so your passed through object won't change. Instead, you need to delete from obj . Also, as prop is dynamic you need to use bracket notation when deleting. Lastly, to check if prop is a property in obj , you can use the in keyword like so:

 function removeProperty(obj, prop) { if (prop in obj) { delete obj[prop]; return true; } return false; } const obj = { prop: "name", age: 20 } const res = removeProperty(obj, "prop"); console.log(obj); console.log(res);

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