简体   繁体   中英

Loop through array of objects, and combine arrays within objects

How can I loop through the data array of objects, and then join each guestList array into a single array to be used elsewhere?

   const data = 
      [
        {
            "guestList": [
                {
                    "firstName": "test",
                    "surname": "test",
                    "email": "test@test.com",
                },
                {
                    "firstName": "test",
                    "surname": "tesT",
                    "email": "test@test.com",
                }
            ],
        },
        {
            "guestList": [
                {
                    "firstName": "test",
                    "surname": "test",
                    "email": "test@test.com",
                },
                {
                    "firstName": "test",
                    "surname": "tesT",
                    "email": "test@test.com",
                }
            ],
        },
        {
            "guestList": [
                {
                    "firstName": "test",
                    "surname": "test",
                    "email": "test@test.com",
                },
                {
                    "firstName": "test",
                    "surname": "tesT",
                    "email": "test@test.com",
                }
            ],
        }
      ]

You can use flatMap and destructuring like this:

 const data =[{"guestList": [{"firstName": "test","surname": "test","email": "test@test.com",},{"firstName": "test","surname": "tesT","email": "test@test.com",}],},{"guestList": [{"firstName": "test","surname": "test","email": "test@test.com",},{"firstName": "test","surname": "tesT","email": "test@test.com",}],},{"guestList": [{"firstName": "test","surname": "test","email": "test@test.com",},{"firstName": "test","surname": "tesT","email": "test@test.com",}],}]; const result = data.flatMap(({guestList}) => guestList); console.log(result);

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