0

I'm trying to grammatically follow a path inside a JSON object, and replace the object with a blank one.

I'm using this method to reach the object desired, and I can verfiy that the object is reached.

$scope.path = "countries.canada.territories.yukon";
$scope.remove = function () {
    var pathInArrayForm = $scope.path.split('.');
    currentObject = $scope.countries;
    for (var i = 0; i < pathInArrayForm.length; i++){
        currentObject = currentObject[pathInArrayForm[i]];
    }
    currentObject.capital = "Montreal";
}

However, when I try to replace the object with a blank one, via

currentObject = {};

Nothing happens. It doesn't change anything! When I use:

currentObject.capital = "Montreal"

it works, but if I just use the object plain, nothing happens.

Please see my JSFiddle: http://jsfiddle.net/ay1wpr5L/2/

My question is, how can I replace an object nested inside other JSON objects, with a blank {}?

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
CodyBugstein
  • 21,984
  • 61
  • 207
  • 363
  • Where's the angularjs tag????????????????????? – Matías Fidemraizer Dec 24 '14 at 09:53
  • 1
    I've re-tagged your question. This isn't about JSON, it's not about passing by reference and it's not a "json path" (what's that? :D). It's just about AngularJS binding. – Matías Fidemraizer Dec 24 '14 at 09:54
  • possible duplicate of [Why isn't this object being passed by reference when assigning something else to it?](http://stackoverflow.com/questions/9437981/why-isnt-this-object-being-passed-by-reference-when-assigning-something-else-to) – simeg Dec 24 '14 at 10:06

1 Answers1

0

Objects are not passed by reference in JS. Read more about the subject here in another question on SO. The best answer I saw was by Alexander Varwijk and he said this:

If you are familiar with pointers, that's an analogy you can take. You're actually passing a pointer, so obj.someProperty would dereference to that property and actually override that, while merely overriding obj would kill off the pointer and not overwrite the object.

To solve your question, just declare the currentObject to $scope.countries like such $scope.countries = currentObject;

Community
  • 1
  • 1
simeg
  • 1,889
  • 2
  • 26
  • 34
  • But `$scope.countries = currentObject;` would replace the whole JSON of countries with just the object for `yukon`. That would be bad – CodyBugstein Dec 24 '14 at 11:11
  • @Imray, then I don't understand what you're trying to achieve. Can you explain some more? – simeg Dec 24 '14 at 12:00