Home > Software engineering >  build simple object from deeply nested array of objects
build simple object from deeply nested array of objects

Time:02-23

I'm having a hard time with this seemingly simple problem. I understand that I can map through the main array and then map again through the items array but when I log the simpleObject variable I don't get anything returned.

I have an array of objects like this

[
    {
        "id": 131186,
        "name": "Section",
        "items": [
            {
                "id": 40455,
                "categories": [
                    {
                        "id": 80313,
                        "name": "some name"
                    },
                    {
                        "id": 80314,
                        "name": "some name"
                    }
                ]
            }
        ]
    },
    {
        "id": 131279,
        "name": "Section",
        "items": [
            {
                "id": 40990,
                "categories": [
                    {
                        "id": 82953,
                        "name": "category"
                    }
                ]
            },
            {
                "id": 40991,
                "categories": [
                    {
                        "id": 82952,
                        "name": "category title"
                    }
                ]
            }
        ]
        
    }
]

and I'm trying to build an array with the object that will look like this

[
    {
        "id": 131186,
        "name": "Section",
        "categories": [
            {
                "id": 80313,
                "name": "some name"
            },
            {
                "id": 80314,
                "name": "some name"
            }
        ]
    },
    {
        "id": 131279,
        "name": "Section",
        "categories": [
            {
                "id": 82953,
                "name": "category"
            },
            {
                "id": 82952,
                "name": "category title"
            }
        ]
    }
]

I tried the following but don't get any results back and not sure why.

    let simpleObject = data.map(({ name, id, items }) => ({
      id,
      name,
      items: items.map((item) => item.categories),
    }));

CodePudding user response:

An example using flatMap

const data = [ { id: 131186, name: "Section", items: [ { id: 40455, categories: [ { id: 80313, name: "some name", }, { id: 80314, name: "some name", }, ], }, ], }, { id: 131279, name: "Section", items: [ { id: 40990, categories: [ { id: 82953, name: "category", }, ], }, { id: 40991, categories: [ { id: 82952, name: "category title", }, ], }, ], }, ];

const output = data.map(({ id, name, items }) => ({
    id,
    name,
    categories: items.flatMap(item => item.categories),
}));

console.log(output);

  • Related