简体   繁体   中英

build simple object from deeply nested array of objects

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),
    }));

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM