Bluefire Bluefire - 2 months ago 6
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
object.a.b.c
), 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

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"]);
console.log(obj.a.b);

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

Comments