Page 1 of 1

Remove Object Property in JavaScript

Posted: Mon Oct 09, 2006 11:10 am
by tomprogers
I'm working in JS, and I want to remove a property from an object I've created. Not just unset it, but remove it completely. I've tried setting the property to undefined, but all that really does it set the property equal to another variable (which is itself undefined).

Code: Select all

var o;

o = {}; view(o);

o = { p: 'I am!' }; view(o);

o.p = null; view(o); // p still exists - not what I want

o.p = undefined; view(o); // doesn't undefine p, tries to set it equal to a variable named "undefined" - also not what I want

function view(o)
{
  var s = 'Inspecting object:\n';
  for(p in o)
    s += p + ': ' + o[p] + '\n';
  alert(s);
  return true;
}
I should mention that the objects I'm working with are much more complex than the obviously simplified example above, and I want very much to avoid redefining each object (but omitting the undesired property) each time I want to remove an attribute.

Any suggestions are appreciated.

Posted: Mon Oct 09, 2006 11:15 am
by Luke
use the delete operator maybe?

Posted: Mon Oct 09, 2006 11:16 am
by tomprogers
Figures. I found the solution: the delete operator.

Code: Select all

var o;

o = {}; view(o);

o = { p: 'I am!' }; view(o);

delete o.p; view(o);

function view(o)
{
  var s = 'Inspecting object:\n';
  for(p in o)
    s += p + ': ' + o[p] + '\n';
  alert(s);
  return true;
}
And it really, really works.

Posted: Mon Oct 09, 2006 11:31 am
by Luke
nice... funny thing is I don't know JACK about javascript... I just read that in the book I just started reading.