Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting nested property in javascript object

Tags:

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.

like image 939
lgc_ustc Avatar asked Nov 21 '16 03:11

lgc_ustc


People also ask

How will you delete the property of the object in JavaScript?

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.

How do you remove a property of 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.

How do I remove a property name from an object?

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.


2 Answers

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;

like image 186
Meligy Avatar answered Sep 28 '22 16:09

Meligy


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); 
like image 32
Dónal Avatar answered Sep 28 '22 18:09

Dónal