mariocasciaro/object-path

A gotcha that might be worth addressing somehow: set() with path=""

Opened this issue · 0 comments

sp00x commented

I guess I wasn't thinking straight when doing this, but I had some code that did objectPath.get(obj.foo, path) and this yields a sensible result when path is "": you get obj.foo

However, then I had code that tried to use set() also with the same path, and that obviously does not work well because it can't change the original reference passed to the method, but probably updates a new object that gets thrown away since nothing is referencing it:

var objectPath = require('object-path');
var a = { b: { c: 1 } };
objectPath.get(a.b, ""); // returns { c: 1 }
objectPath.set(a.b, "", "hi"); // returns { c: 1 } - but a.b is still { c: 1 }, not "hi"
objectPath.set(a, "b", "hi"); // returns { c: 1 } AND a.b. is set to "hi"

As a work-around I ended up doing something like (I did this to preserve other references to the same 'obj' elsewhere):

if (path == "")
{
  // quick hack for objects
  for (var p in obj) delete obj[p];
  for (var p in value) obj[p] = value[p];
}
else
  objectPath.set(obj, path, value);

Obviously this would only work for objects and noe value types, so I'm not sure what a consistent solution here is.

Since it now just passes silently but does not do what one intends, maybe an error should be thrown instead if the path is blank?