[英]Replace word with another word in long string in nested array
我的路徑如下圖所示:
Node : /myPath/Node
Node-1 : /myPath/Node/Node-1
Node-1-1 : /myPath/Node/Node-1-1
現在,如果我當前的對象記錄來自Node,那么我想從該節點遍歷它的每個子節點,並用First替換Node。
預期輸出為:
Node : /myPath/First
Node-1 : /myPath/First/Node-1
Node-1-1 : /myPath/First/Node-1-1
對於我當前的代碼問題,它只是替換第一個節點上的搜索詞(第一個) ,而不是替換每個子節點。
var currentObj = { "name": "Node", "nodes": [ { "name": "Node-1", "nodes": [ { "name": "Node-1-1", "nodes": [ { "name": "Node-1-1-1", "nodes": [ ], "path": "/myPath/Node/Node-1/Node-1-1/Node-1-1-1" } ], "path": "/myPath/Node/Node-1/Node-1-1" } ], "path": "/myPath/Node/Node-1" } ], "path": "/myPath/Node" }; recursive(currentObj,"First"); console.log(currentObj); function recursive(node,replace) { console.log(node.path); node.path = replaceAll(node.path,'Node',replace); } function replaceAll(str, find, replace) { return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } function escapeRegExp(str) { return str.replace(/([.*+?^=!:${}()|\\[\\]\\/\\\\])/g, "\\\\$1"); }
遞歸調用recursive
對各節點nodes
似乎工作:
function recursive(node)
{
node.path = replaceAll(node.path,'Node','First');
node.nodes.forEach(recursive);
}
帶有額外的參數:
node.nodes.forEach(function(child_node) {
recursive(child_node, arg1, arg2);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.