JavaScript Delete Keyword and JSON Serialization

Every now and then we run into a situation where we think if I knew a little bit more about this technology, it would have saved me a LOT of time.

This happened to me few days back. I was working with a large chunk of JSON out of which I needed a little piece sent back to server and it took me some time to figure out a way to do it.

I used delete keyword and got rid of extra properties from the object graph before I converted it to JSON. Here is a quick sample I whipped up for this post.

PS: Due to certain restrictions the following code snippet is missing appropriate closing script tags. Kindly add them if you copy the code to use it somewhere.


function GetPersons() { var persons = new Array() persons.push(GetPerson("Bruce", "Wayne")); persons.push(GetPerson("Clark", "Kent")); return persons; };

GenerateFullJSON = function () { $('#output').val(JSON.stringify(GetPersons())); };

GeneratePartialJSON = function () { var persons = GetPersons(); $(persons).each(function (index, person) { for (var property in person) { if (property === "LastName") { delete person[property]; } } }); $('#output').val(JSON.stringify(persons)); };