如何在 Java 脚本中从字符串创建对象树

how to create object tree from string in java script

本文关键字:字符串 创建对象 脚本 Java      更新时间:2023-09-26

嗨,在javascript中,我必须从字符串创建对象树,如下所示

"组 1:节点 1:属性,组 1:节点 2:属性,组 2:节点 2:属性,组 2:节点3:属性,组 2:节点 1:属性

,组 3:节点 2:属性"。

在此,属性也是:分离的,

我需要如下对象树

组 1   节点 1     性能   节点2     性能组2   节点2     性能   节点3     性能   节点 1     性能组3   节点2     性能

任何人都可以告诉我用例子做到这一点的最佳方式是什么。

虽然这看起来像是学校的练习...我认为你需要看看split()方法。首先在逗号 (,) 上拆分,然后拆分冒号 (:)。例如。。

看看这个:http://jsfiddle.net/T852c/

var str = 'group1:node1:properties,group1:node2:properties,group2:node2:properties,group2:node3:properties,group2:node1:properties,group3:node2:properties';
var result ={},
    groups = str.split(','),
    groupsCount = groups.length; 
for(var i=groupsCount; i--;){
    var groupStr = groups[i],
        split = groupStr.split(':'),
        groupKey = split[0],
        nodeKey = split[1],
        properties = split[2],
        group = result[groupKey] || (result[groupKey] = {}),
        node = group[nodeKey] || (group[nodeKey] = {});
    
    node[properties] = { foo: 'bar' };    
}
console.log(result);

它可能不完全是您正在寻找的,但它可能有助于您入门。祝你好运!