Remove Object Property in JavaScript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
tomprogers
Forum Commoner
Posts: 50
Joined: Fri Mar 17, 2006 5:17 pm
Location: Minnesota
Contact:

Remove Object Property in JavaScript

Post 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.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

use the delete operator maybe?
tomprogers
Forum Commoner
Posts: 50
Joined: Fri Mar 17, 2006 5:17 pm
Location: Minnesota
Contact:

Post 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.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

nice... funny thing is I don't know JACK about javascript... I just read that in the book I just started reading.
Post Reply