My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

JavaScript Nestify Function

Gokul N K's photo
Gokul N K
·Jun 7, 2018

I recently had a requirement in a project where I had to convert a flat JSON object into a nested JSON object. Instead of explaining the problem statement I will share a set of input and output arrays so that the requirement becomes clear.

const input1 = [{
        pos: 1,
        text: 'Andy'
    },
    {
        pos: 1,
        text: 'Harry'
    },
    {
        pos: 2,
        text: 'David'
    },
    {
        pos: 1,
        text: 'Lisa'
    },
];
const output1 = [{
        pos: 1,
        text: 'Andy'
    },
    {
        pos: 1,
        text: 'Harry',
        children: [{
            pos: 2,
            text: 'David'
        }]
    },
    {
        pos: 1,
        text: 'Lisa'
    }
];

const input2 = [{
        pos: 1,
        text: 'Andy'
    },
    {
        pos: 1,
        text: 'Harry'
    },
    {
        pos: 2,
        text: 'David'
    },
    {
        pos: 2,
        text: 'Edger'
    },
    {
        pos: 1,
        text: 'Lisa'
    },
];
const output2 = [{
        pos: 1,
        text: 'Andy'
    },
    {
        pos: 1,
        text: 'Harry',
        children: [{
                pos: 2,
                text: 'David'
            },
            {
                pos: 2,
                text: 'Edger'
            }
        ]
    },
    {
        pos: 1,
        text: 'Lisa'
    }
];

const input3 = [{
        pos: 1,
        text: 'Andy'
    },
    {
        pos: 1,
        text: 'Harry'
    },
    {
        pos: 2,
        text: 'David'
    },
    {
        pos: 3,
        text: 'Dexter'
    },
    {
        pos: 2,
        text: 'Edger'
    },
    {
        pos: 1,
        text: 'Lisa'
    },
];
const output3 = [{
        pos: 1,
        text: 'Andy'
    },
    {
        pos: 1,
        text: 'Harry',
        children: [{
                pos: 2,
                text: 'David',
                children: [{
                    pos: 3,
                    text: 'David'
                }]
            },
            {
                pos: 2,
                text: 'Edger'
            }
        ]
    },
    {
        pos: 1,
        text: 'Lisa'
    }
];

I am working on a solution. I am thinking if it makes sense to use recursion for this or if an alternate approach is better. I will post the solution once I solve it. But would love to have inputs from others as well :)