-1

How do I set object references of one type with another object reference in a deeply nested object?

// Following is the class
class Ab{ a: number; }

let x = new Ab();
x.a = 10;

// Now I have an object something like this
let obj  = {
    b: 'hello',
    c: new Ab(),
    d: {
        x: 5,
        y: new Ab(),
        z: {
           p: new Ab()
        } 
    }
} 

Now I should be able to change all the references of new Ab() set to x object.

let obj  = {
    b: 'hello',
    c: x, // reassign the x reference
    d: {
        x: 5,
        y: x,
        z: {
           p: x
        } 
    }
} 

I think I have to go with deep cloning the object. I was using lodash

lodash.cloneDeepWith(obj, val => {
    // please do not worry/consider these logic this condition is working
    if (Object.getPrototypeOf(val) === tc) {
       // Actual problem is here
       // reassigning is not changing the original reference of obj
       val = x;
    }
});

Are there any solutions out there which are faster and easier? Any help is appreciated.

user3205479
  • 1,443
  • 1
  • 17
  • 41
  • Refer https://stackoverflow.com/questions/2549320/looping-through-an-object-tree-recursively/2549333?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – user3205479 May 08 '18 at 19:55

1 Answers1

1

The following code will recursively change each object based on the instance type:

const changeObjects = (obj, replacement, className) => {
  Object.keys(obj).forEach((key) => {
    if (obj[key] instanceof className) {
      obj[key] = replacement;
    } else if (typeof obj[key] === 'object') {
      changeObjects(obj[key], replacement, className);
    }
  });
}

changeObjects(obj, x, Ab);

That code should work with the example you gave without creating a deep clone. If you did want to clone the replacement and not have circular references you could do this as well:

obj[key] = Object.assign({}, replacement);

when assigning the replacement.

I'm not sure if this qualifies as easier, but it is a bit faster and does the job you need it to do.

TCool
  • 163
  • 1
  • 6
  • Perfect. Thank you. I was looking at the same solution here https://stackoverflow.com/questions/2549320/looping-through-an-object-tree-recursively/2549333?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – user3205479 May 08 '18 at 19:54