3

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

0

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

1 Comment

This is awesome! Thanks

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.