1

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).

1
  • 2
    "All keys should not be in a string type" The keys of an object are either a string or a Symbol Commented Nov 21, 2019 at 10:12

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.