我正在尝试通过删除重复键来更改json的结构。否则,将同名子代仅放在一个名称节点中。
当前JSON:
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{
"name": "AgglomerativeCluster",
"size": [
"3938"
]
}
]
}
]
},
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{
"name": "CommunityStructure",
"size": [
"3812"
]
}
]
}
]
}
]
}
所需的输出:
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{
"name": "AgglomerativeCluster",
"size": 3938
},
{
"name": "CommunityStructure",
"size": 3812
}
]
}
]
}
]
};
感谢您的帮助。
答案 0 :(得分:2)
通常,StackOverflow并不是让人们为您编写代码的地方,并且您的问题应该更具体地说明遇到问题的算法的哪一部分。但是,这看起来很有趣,所以我做到了。
我首先将其转换为一个对象,该对象的属性是名称,值是子代/大小,从而解决了这个问题。这样可以确保每个命名实例都与其他命名实例组合在一起。
var mutate = function(desired, current) {
for (var x = 0; x < current.length; x++) {
if (Object.hasOwnProperty.call(current[x], 'size')) {
desired[current[x].name] = parseInt(current[x].size[0], 10);
}
else {
if (!Object.hasOwnProperty.call(desired, current[x].name)) {
desired[current[x].name] = Object.create(null);
}
mutate(desired[current[x].name], current[x].children);
}
}
return desired;
};
然后我通过遍历Object.entries
(键/值对)将其转换回您想要的原始格式。
var mutate2 = function(current) {
var desired = [];
var entries = Object.entries(current);
for (var x = 0; x < entries.length; x++) {
var o = Object.create(null);
o.name = entries[x][0];
if (typeof entries[x][1] === 'number') {
o.size = entries[x][1];
}
else {
o.children = mutate2(entries[x][1]);
}
desired.push(o);
}
return desired;
};
使用这种可怕的野兽可以得到结果:
var desiredJson = mutate2(mutate(Object.create(null), [ currentJson ]));
console.log(desiredJson);