0

i have a data like this

let data = [
    {
        id: 1,
        name: "1"
    },
    {
        id: 2,
        name: "2",
        idParents: 1
    },
    {
        id: 3,
        name: "3",
        idParents: 2
    },
    {
        id: 4,
        name: "4",
        idParents: 1
    }
]

and i need to convert it to data like this

let formatedData = [
    {
        id: 1,
        name: "1",
        childrens: [
            {
                id: 2,
                name: "2",
                childrens: [
                    {
                        id: 3,
                        name: "3"
                    }
                ]
            },
            {
                id: 4,
                name: "4"
            }
        ]
    },
]

i am a newbie in code, can anyone show me a example in any programing language so i can prefer. Every example in stackoverflow come with input is an object so i am so confused. Thanks a lot.

sonphung.xf
  • 107
  • 8

1 Answers1

1

You're new here, so you might not understand that generally we want to see your own effort before offering help. But I happened to have something much like this lying around:

const makeForest = (xs, id) => 
  xs .filter (x => x.idParents == id) 
     .map ((x) => {
       const children = makeForest (xs, x.id)
       return {
         ... x,
         ... (children.length ? {children} : {}) 
       }
     })

let data = [{id: 1, name: "1"}, {id: 2, name: "2", idParents: 1}, {id: 3, name: "3", idParents: 2}, {id: 4, name: "4", idParents: 1}]

console .log (makeForest (data))
console .log (makeForest (data) [0])
.as-console-wrapper {max-height: 100% !important; top: 0}

There is no clear-cut guarantee that there is only one root node in the data, so the function here creates a forest, that is a collection of trees. If you know for sure that there will only be one root node, then you can just take the first element ([0]) of the result.

This is called based on the root node(s) not having a idParent property. If they, for instance had a 0 or -1 or null value, you can just pass that as a second parameter to makeForest.

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103