繁体   English   中英

用嵌套数组中长字符串中的另一个单词替换单词

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM