简体   繁体   中英

convert nested object in parent / children structure js

I try to convert this structure (each child is property in object):

 const tree = { "Parent 1": { "Children1": { "Children2": { "#1": { info: {}}, "#2": { info: {}}. "#3": { info: {}} }, "Children1-1": { "Children2-2": { "#1": { info: {}}, "#2": { info: {}}. "#3": { info: {}} } }, "Parent 2": {... } };

In to this tree structure with parent child view. But in the end of my tree i don't need childrens

 const resultTeee = [ { name: 'Parent 1', children: [ { name: 'Children 1', children: [ { name: 'Children 2', children: [ {name: "#1", info: {}}, {name: "#2", info: {}} ] } ] }, { name: 'Children 1-1', children: [ { name: 'Children 2-2', children: [ {name: "#1", info: {}}, {name: "#2", info: {}} ] } ] } ] }, { name: 'Parent 2'.... } ]

I try "traverse tree" approach but can't understand how to switch for new children path. Object can have multiple nested structure on each level.

const toArrayTree = (obj) => {
    return Object.keys(obj).map(key => {
        return {name: key, children: [toArrayTree(obj[key])]}
    })
}

object for testing

const tree = {
    "Parent 1" : {
        "Children1": {
            "Children2": {
                "#1": { info: {}},
                "#2": { info: {}},
                "#3": { info: {}},
            }
        },
    },
    "Parent 2" : {
        "Children2.1": {
            "Children2.2": {
                "#4": { info: {}},
                "#5": { info: {}},
                "#6": { info: {}},
            }
        },
    },
};

But as @adiga said, why the last branch of tree is not { name: 'info', children: [] } ?

Update on solution

const toArrayTree = (obj) => {
    return Object.keys(obj).map(key => {
        return typeof obj[key] === 'object' ?
            {name: key, children: [toArrayTree(obj[key])]} :
            {name: key, [key]: obj[key]};
    })
}

It's really bad idea to use Object(v) === v , because it would be true for v being function for example

You could map the entries of the object. If the value is an object, recursively call the function.

 const tree = {"Parent 1":{Children11:{Children111:{"#1":{info:{}},"#2":{info:{}},"#3":{info:{}}}}},"Parent 2":{Children21:{Children211:{"#1":{info:{}},"#2":{info:{}},"#3":{info:{}}}}}}; function trasnform(o) { return Object.entries(o).map(([name, v]) => Object(v) === v? { name, children: trasnform(v) }: { name, value: v } // unclear from the question ) } console.log(trasnform(tree))

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