嗨,在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);
它可能并非您要找的东西,但可能有助于您入门。祝你好运!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句