简体   繁体   中英

Converting parent / children structure to object

I need to convert js object like this:

{
    "id": 1,
    "name": "A",
    "parent": null,
    "children": [
        {
            "id": 2,
            "name": "B",
            "parent": 1,
            "children": []
        },
        {
            "id": 3,
            "name": "C",
            "parent": 1,
            "children": [
                {
                    "id": 4,
                    "name": "D",
                    "parent": 3,
                    "children": []
                }
            ]
        }
    ]
}

to another like this:

{
    "А": [
        {
            "B": "value",
            "C": [
                {
                    "D": "value"
                }
            ]
        }
    ]
}

I wrote the function, but it returns the wrong object with several nested arrays:

const convert = (obj) => {
    return obj.map((i) => {
        return Object.keys(i).filter(y => y === 'name').map(key => {
            return i['children'].length > 0 ? { [i[key]]: convert(i['children']) } : { [i[key]]: 'value' }
        });
    })
};

How to change my implementation for getting the right object?

You could build the entries from objects and map nested children, if exists.

 const transform = array => Object.fromEntries(array.map(({ name, children }) => [name, children.length? [transform(children)]: 'value'] )), data = { id: 1, name: "A", parent: null, children: [{ id: 2, name: "B", parent: 1, children: [] }, { id: 3, name: "C", parent: 1, children: [{ id: 4, name: "D", parent: 3, children: [] }] }] }, result = transform([data]); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM