I have a JS object like this:
var tenants = {     'first': {         'name': 'first',         'expired': 1     },     'second': {         'name': 'second'     } }   And I'd like to delete the 'expired' property of tenant 'first', should I just do this?
delete tenants['first']['expired'];   Note: this question is more specific than the question: How do I remove a property from a JavaScript object?, in that my question focuses on the 'nested' part.
Answer: Use the delete Operator You can use the delete operator to completely remove the properties from the JavaScript object. Deleting is the only way to actually remove a property from an object.
The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.
The delete operator is used to remove these keys, more commonly known as object properties, one at a time. The delete operator does not directly free memory, and it differs from simply assigning the value of null or undefined to a property, in that the property itself is removed from the object.
Yes. That would work.
delete tenants['first']['expired']; or delete tenants.first.expired;.
If you are deleting it only because you wanted to exclude it from JSON.stringify(), you can also just set it to undefined, like tenants['first']['expired'] = undefined;
If the property you want to delete is stored in a string, you can use this function
function deletePropertyPath (obj, path) {    if (!obj || !path) {     return;   }    if (typeof path === 'string') {     path = path.split('.');   }    for (var i = 0; i < path.length - 1; i++) {      obj = obj[path[i]];      if (typeof obj === 'undefined') {       return;     }   }    delete obj[path.pop()]; };   Example Usage
var tenants = {     'first': {         'name': 'first',         'expired': 1     },     'second': {         'name': 'second'     } }  var property = 'first.expired';     deletePropertyPath(tenants, property); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With