我有一个对象文字,如下所示
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'
我想我需要将字符串拆分为'。'然后计算有多少'^'然后从绝对路径的末尾'弹出'那么多步但我不确定在没有编写大的递归函数的情况下最好的方法呢
答案 0 :(得分:1)
由于您的路径实际上只是带有分隔符.
的字符串,因此我会对它们进行操作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"