【问题标题】:Javascript use a relative string path to traverse another string pathJavascript 使用相对字符串路径来遍历另一个字符串路径
【发布时间】:2016-09-19 01:18:09
【问题描述】:

我有一个如下所示的对象字面量

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'

我想我需要在 '.' 上拆分字符串然后计算有多少“^”,然后从绝对路径的末尾“弹出”那么多步,但我不确定在不编写大型递归函数的情况下执行此操作的最佳方法

【问题讨论】:

    标签: javascript path relative-path traversal


    【解决方案1】:

    由于您的路径实际上只是带有分隔符. 的字符串,因此我会像这样对它们进行操作。 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"
    

    【讨论】:

    • 这太棒了!谢谢
    猜你喜欢
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 2010-10-14
    • 2011-06-27
    • 2014-10-29
    • 2020-05-18
    • 2019-03-04
    相关资源
    最近更新 更多