Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
sp00x opened this issue Jun 5, 2015 · 0 comments
Open

Comments

@sp00x
Copy link

sp00x commented Jun 5, 2015

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant