Create a recursive Json object from categories to display on the website menu

Joined
Aug 27, 2022
Messages
1
Reaction score
0
I created a categories document in mongodb like this

JSON:
{

    id: 1,

    name: 'digital',

    parent: null

},

{

    id: 3,

    name: 'tv',

    parent: 1

},

{

    id: 4,

    name: 'samsung',

    parent: 3

},

{

    id: 2,

    name: 'kitchen',

    parent: null

},

{

    id: 5,

    name: 'electronic',

    parent: 2

}

While Thanking the forum, i had a request a aggregate command to reach this Json
JSON:
[

  {

    "id": 1,

    "name": "digital",

    "children":[

      {

        "id": 3

        "name": "tv",

        "children": [

          {

            "id": 4,

            "name": "samsung",

            "children": []

          }

        ]

      }

    ]

  },

  {

    "id": 2,

    "name": "kitchen",

    "children": [

      {

        "id": 5,

        "name": "electronic",

        "children": []

      }

    ]

  }

]

In all records, the children field needs to be identified.
I will be very grateful for your answers.
 
Joined
Nov 13, 2020
Messages
302
Reaction score
38
Please check your json array with mine to find your errors. I just gave you the ids of the children and the last reveal was looking at the last empty child so you can see how to get the others. Any questions?

Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
    <p id="here"></p>
    <p id="there"></p>
    <p id="nowhere"></p>
    <p id="nothere"></p>
<script>

var myArray = [
    {
        "id": 1,
        "name": "digital",
        "children":[
        {
            "id": 3,
            "name": "tv",
            "children": [
                {
                    "id": 4,
                    "name": "samsung",
                    "children": []
                }
            ]
        }
        ]
    },
    {
        "id": 2,
        "name": "kitchen",
        "children": [
            {
                "id": 5,
                "name": "electronic",
                "children": []
            }
        ]
    }
]
document.getElementById('here').innerHTML = myArray[0].children[0].id;
document.getElementById('there').innerHTML = myArray[0].children[0].children[0].id;
document.getElementById('nowhere').innerHTML = myArray[1].children[0].id;
document.getElementById('nothere').innerHTML = myArray[1].children[0].children[0];
</script>
</body>
</html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top