Bluefire Bluefire - 1 year ago 59
Javascript Question

Delete an object's property given its location

Given the location of a property of an object in the form of an array (

[a, b, c]
corresponding to
), how can I execute the equivalent of the statement
delete object.a.b.c

EDIT: to clarify, I want to write a function that looks like this:

function deleteProperty(object, location) {
// do stuff

and has the following effect:

var obj = {"foo": "FOO", "bar": "BAR", "a": {"b": "B"}};
deleteProperty(obj, [a, b]);
typeof obj.a.b === "undefined";

Answer Source

You need to use bracket notation and loop over until you get to the last one, then use the last one for the delete.

function deleteProperty(obj, loc) {
  var last = loc.pop(); //grab last item from array
  var x = loc.reduce(function(o, x) {  //walk obj until all properties are there
    return o[x];
  }, obj);
  delete x[last];  //delete the last item from the array

var obj = {
  "foo": "FOO",
  "bar": "BAR",
  "a": {
    "b": "B"
deleteProperty(obj, ["a", "b"]);

The code assumes that the path will be there, there are no checks for null/undefined/invalid path.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download