Search code examples
javascriptpathrelative-pathtraversal

Javascript use a relative string path to traverse another string path


I have an object literal that looks like below

var object = {
   child:[{
       actualChild:'valueIwantToGet'
       medical:{
           contact:'where i am starting my relative path'
       }
   }]
}

My question is how can i alter an absolute path string with a relative path string to get a new path where '^' would be one level above (parent)

var absolutePath = 'object.child.0.medical.contact';
var relativePath = '^.^.actualChild';

//The String i am trying to get
'object.child.0.actualChild'

I figure i need to split the string on '.' then count how many '^' there are and then 'pop' that many steps from the end of the absolute path but i'm not sure on the most optimal way to do this without writing a large recursive function


Solution

  • Since your paths are actually just strings with delimiter ., I would operate on them as such e. g. via regex:

    function realPath(path) {
        var result = path;
        while ((path = path.replace(/[^\.]*\.\^\./g, '')) !== result) result = path;
        return result;
    }
    

    Example:

    realPath('object.child.0.medical.contact.^.^.actualChild');
    

    Result:

    "object.child.0.actualChild"