javascriptreactjsarraysobjectpopulation

How can I populate an array of object from another array of object and create a new array of obj?


There are two arrays of objects. One contains some random menu. And the second one contains id of first array element and it indicates which one element of first will array will be head menu and which will be child menu. Suppose Id 1 Home will be head menu. id 2, 3 (Home page 1, Home page 2) will be child menu.

I have to populate those element through id and have to create a third array of object from those array so that I can easily render them in react component dynamically.

How can I do that?

I yet to understand how can I start.

const menus = [
    {
        id: 1,
        text: 'Home',
        link: '#'
    },
    {
        id: 2,
        text: 'Home page 1',
        link: '#'
    },
    {
        id: 3,
        text: 'Home page 2',
        link: '#'
    },
    {
        id: 4,
        text: 'Shop',
        link: '#'
    },
    {
        id: 5,
        text: 'two column',
        link: '#'
    },
    {
        id: 6,
        text: 'single column',
        link: '#'
    },
]

const childrenMap = [
    {
        parent: 1,
        chilren: [2, 3]
    },
    {
        parent: 4,
        children: [5, 6]
    }
]

Solution

  • use reduce to build a new array. use find to find the matching ids.

    const menus = [
        {
            id: 1,
            text: 'Home',
            link: '#'
        },
        {
            id: 2,
            text: 'Home page 1',
            link: '#'
        },
        {
            id: 3,
            text: 'Home page 2',
            link: '#'
        },
        {
            id: 4,
            text: 'Shop',
            link: '#'
        },
        {
            id: 5,
            text: 'two column',
            link: '#'
        },
        {
            id: 6,
            text: 'single column',
            link: '#'
        },
    ]
    
    const childrenMap = [
        {
            parent: 1,
            children: [2, 3]
        },
        {
            parent: 4,
            children: [5, 6]
        }
    ]
    
    const result = childrenMap.reduce((p, c) =>
        p.concat({ parent: menus.find(m => m.id === c.parent), children: c.children.map(cc => menus.find(m => m.id === cc)) }), []
    );
    
    console.log(result);