Search code examples
javascriptarraysjsondeep-diff

How to find object value from property path in Javascript object


I explain the problem with sample.

For example i have javascript object. It looks like:

var trial= { points:[{x:1,y:2},{x:5,y:2},{x:3,y:4}] , obj:{id:5,name:"MyName"} }

I use deep diff module to find difference between two json array. Then it find the differences and find difference path. If value of x is changed, then it finds.

For example

path = ["points",0,"x"] 
or
path= ["obj","name"]

So my question is that how to generate json object from these path.

For example i have to generate that

trial.points[0].x        or    trial.obj.name  

How to do that ? thank you for your answer.


Solution

  • You can do like this:

    var trial= { points:[{x:1,y:2}, {x:5,y:2},{x:3,y:4}] , obj:{id:5,name:"MyName"}};
    var path = ["points", 0, "x"];
    
    var object = trial;
    path.map(field => object = object[field]);
    
    console.log(object);
    
    path = ["obj", "name"];
    
    var object = trial;
    path.map(field => object = object[field]);
    console.log(object);