Javascript使用相对字符串路径遍历另一个字符串路径
Javascript use a relative string path to traverse another string path
我有一个如下所示的对象文字
var object = {
child:[{
actualChild:'valueIwantToGet'
medical:{
contact:'where i am starting my relative path'
}
}]
}
我的问题是如何用相对路径字符串更改绝对路径字符串以获得新路径,其中“^”将比(父级)高一级
var absolutePath = 'object.child.0.medical.contact';
var relativePath = '^.^.actualChild';
//The String i am trying to get
'object.child.0.actualChild'
我想我需要在“.”上拆分字符串然后计算有多少'^',然后 'pop' 从绝对路径的末尾算起那么多步骤,但我不确定在不编写大型递归函数的情况下以最佳方式做到这一点
因为你的路径实际上只是带有分隔符 .
的字符串,我会像这样对它们进行操作 e。 G。通过正则表达式:
function realPath(path) {
var result = path;
while ((path = path.replace(/[^\.]*\.\^\./g, '')) !== result) result = path;
return result;
}
示例:
realPath('object.child.0.medical.contact.^.^.actualChild');
结果:
"object.child.0.actualChild"
我有一个如下所示的对象文字
var object = {
child:[{
actualChild:'valueIwantToGet'
medical:{
contact:'where i am starting my relative path'
}
}]
}
我的问题是如何用相对路径字符串更改绝对路径字符串以获得新路径,其中“^”将比(父级)高一级
var absolutePath = 'object.child.0.medical.contact';
var relativePath = '^.^.actualChild';
//The String i am trying to get
'object.child.0.actualChild'
我想我需要在“.”上拆分字符串然后计算有多少'^',然后 'pop' 从绝对路径的末尾算起那么多步骤,但我不确定在不编写大型递归函数的情况下以最佳方式做到这一点
因为你的路径实际上只是带有分隔符 .
的字符串,我会像这样对它们进行操作 e。 G。通过正则表达式:
function realPath(path) {
var result = path;
while ((path = path.replace(/[^\.]*\.\^\./g, '')) !== result) result = path;
return result;
}
示例:
realPath('object.child.0.medical.contact.^.^.actualChild');
结果:
"object.child.0.actualChild"