我正在尝试从这种格式在客户端转换我的数据:
[{
"id": 1,
"name": "dad",
"parent": [],
"children": [{
"group": {
"id": 2,
"name": "child1",
"parent": [{
"parent": 1
}]
}
},
{
"group": {
"id": 3,
"name": "child2",
"parent": [{
"parent": 1
}]
}
},
{
"group": {
"id": 8,
"name": "child3",
"parent": [{
"parent": 1
}]
}
}
]
}]
为这种格式:
[{
id: 1,
name: "parent",
parent: null,
children: [{
id: 2,
name: "child1",
parent: {
id: 1
},
children: []
},
{
id: 3,
name: "child2",
parent: {
id: 1
},
children: []
}
]
}]
要点:
- 所有的键都不能是字符串类型
- “ parent ”应该只包含 parent 的 ID
- 'group' 对象应该被删除 - 它的内容应该只是 代替他
我在 npm 中找不到要使用的转换库,我需要数据采用那种格式才能在“react-vertical-tree”组件中使用(在中找不到任何其他好看的垂直树组件使用react)。
最佳答案
您可以使用转换后的部分映射新对象。
const convert = o => {
var children;
if ('group' in o) o = o.group;
if ('children' in o) children = o.children.map(convert);
return Object.assign({}, o, { parent: o.parent.length ? { id: o.parent[0].parent } : null }, children && { children });
};
var data = [{ id: 1, name: "dad", parent: [], children: [{ group: { id: 2, name: "child1", parent: [{ parent: 1 }] } }, { group: { id: 3, name: "child2", parent: [{ parent: 1 }] } }, { group: { id: 8, name: "child3", parent: [{ parent: 1 }] } }] }],
result = data.map(convert);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 在javascript中将树从graphql格式转换为json格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58972310/