簡體   English   中英

正則表達式:具有數組支持的拆分對象表示法路徑字符串

[英]Regex: split object notation path string with array support

我有一個遞歸函數來遍歷一個對象,並使用像jsonObj.object.item.value這樣的路徑字符串來獲取所需的jsonObj.object.item.value 我們的想法是以某種方式升級它以支持數組。

const getValue = function(pathVar, obj) {
  obj = obj || x;
  // get very first node and the rest
  let [node, restNodes] = pathVar.split(/\.(.+)/, 2)
  // get interim object
  ret = obj[node];
  if(ret === undefined) return undefined;
  // pass rest of the nodes further with interim object
  if(restNodes) return getValue(restNodes, ret);
  return ret;
};

現在,在每次迭代時,簡單的regexp將路徑字符串(如jsonObj.object.item.valuejsonObjobject.item.value

我的想法是在這里添加數組支持,所以我可以進行轉換

car.engine.something => car and engine.something
wheels[2].material.name => wheels[2].material.name
[2].material.name => 2material.name
car.wheels[4] => carwheels[4]

有什么想法怎么做?

你可以使用eval來評估表達式。 至於功能方法,請使用以下內容。

function getValue(path, obj) {
    obj = obj || self; // self is the global window variable
    if( !path )
        return obj;

    let pattern = /(?:\["?)?(\w+)(?:\.|"?])?(.*)/i;

    let [ full, property, rest ] = path.match(pattern);
    return getValue( rest, obj[ property ] );
}

self.obj = { foo: [ 2, {bar: "baz"} ] };
console.log(getValue('obj.foo[1]["bar"]')) // 'baz'

模式使用四組。 第一個是非捕獲並期望可能["這將有助於匹配數組或對象屬性。然后我們期望我們捕獲的一系列字母數字。然后另一個非捕獲組要么關閉"]或匹配a . 最后,我們捕獲其余部分以用於下一次調用。

eval再次具備了這一切能力。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM