javascript - 在javascript中将树从graphql格式转换为json格式

标签 javascript json reactjs npm tree

我正在尝试从这种格式在客户端转换我的数据:

[{
    "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: []
        }
    ]
}]

要点:

  1. 所有的键都不能是字符串类型
  2. “ parent ”应该只包含 parent 的 ID
  3. '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/

相关文章:

python - 使用 Python 将嵌套 JSON 转换为 Excel

reactjs - 为什么使用 findBy 时测试失败而使用 waitfor 时测试成功?

reactjs - Amplify React Native - 使用 amplify add api 出现重复错误

javascript - Babel 加载程序无法识别 es2015 代码

javascript - 尝试创建仅显示 3 个 div 的打印页面

javascript - 如何清除单选按钮?

javascript - 有没有办法防止框架覆盖主窗口?

c# - 如何从复杂的 Json 对象中获取值?

javascript - API 设计 - 存储像 HTML 这样的富文本的最佳实践是什么

javascript - 如何运行 npm 的示例