teamdever
teamdever

Reputation: 372

Transform tree from graphql format to json format in javascript

I'm trying to transform my data on client side from this format:

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

to this format:

[{
    id: 1,
    name: "parent",
    parent: null,
    children: [{
            id: 2,
            name: "child1",
            parent: {
                id: 1
            },
            children: []
        },
        {
            id: 3,
            name: "child2",
            parent: {
                id: 1
            },
            children: []
        }
    ]
}]

key points:

  1. All keys should not be in a string type
  2. The 'parent' should just include the id of the parent
  3. 'group' object should be removed - and its contents should just replace him

I can't find a transformation library in npm to use and i need the data to be in that exact format to use in 'react-vertical-tree' component (didn't find any other good looking vertical tree component in react).

Upvotes: 1

Views: 127

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386540

You could map new objects with converted parts.

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; }

Upvotes: 1

Related Questions