2

I have a fairly complex nested object, for example:

A = {b : {c : { d : [{e:false},{g:true}] } } }

And through some algorithm I have found d

Now I have a clone of A, Z = clone(A)

I want to be able to modify the d in Z. How can I somehow store the position of d, so that I can go to that position in Z and modify it. If this were a list I could just store the index and modify at the same index. I could of course search the tree for d, but I cannot assume unique property names, and even if I could this would be slow

Any ideas?

3
  • Store a property stack as you find D. Commented Jan 13, 2012 at 23:44
  • d doesn't have a position in Z, so you can't - properties of objects in javascript doesn't have fixed positions, objects cannot be sorted for the same reason. the only way for you to interact with it is through its name, which btw you can safely assume is unique for that object, since a js object cannot have two separate properties with the same name. Commented Jan 13, 2012 at 23:47
  • Thanks. By uniquness I mean something like this a = {b:[{b:true},1]}. You could not 'search' for b in this case, but as you said I must interact through the name Commented Jan 13, 2012 at 23:55

2 Answers 2

3

While your algorithm finds d, create a collection of properties to specify how d can be found. In this case, it would look like so

["b", "c", "d"]

Then you can loop through the collection to traverse Z for the clone of d:

properties = ["b", "c", "d"];
newD = Z;
for(var i = 0; i < properties.length; i++){
  newD = newD[properties[i]];
}
Sign up to request clarification or add additional context in comments.

Comments

0

If I understand correctly, what you are seeking is a path to d -- "b.c.d". So if you have d--

//untested, should return path in dot notation b.c.d
function findPath(o,t,n,p){
  if (typeof p=='undefined') {
    p='';
  }
  if (typeof n=='undefined') {
    n='';
  }
  if (o===t) {
    if (p=='') {
      return n;
    }else{
      return p+'.'+n;
    }
  }
  if (typeof o!='object') {
    return p;
  }
  for (var i in o) {
    var j=o[i];
    var xp=p;
    p=findPath(j,d,i,p);
    if (xp!=p) {// found
      return p;
    }
  }
  return p;
}
// call it
var s=findPath(A,d);
// s="b.c.d"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.