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.

3

1 Answer 1

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.

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

1 Comment

See also a generalization of this in another answer.

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.