Search code examples
javascriptarrays

Extract values from arrays in


I have a response object that I'm wanting to extract all of the id values out, but I'm not sure the best way to go about it...

const obj = {
  "responseArray":[
    {
      "accounts":[
        {
          "products":[
            {
              "id":"123",
            }
          ]
        },
        {
          "products":[
            {
              "id":"456",
            }
          ]
        }
      ]
    },
    {
      "accounts":[
        {
          "products":[
            {
              "id":"987",
            }
          ]
        },
        {
          "products":[
            {
              "id":"654",
            }
          ]
        }
      ]
    }
  ]
}

The closest I've gotten is with mapping

const mapped = obj.responseArray.map(item => item?.accounts.map(acc => acc.products.map(prod => prod.id)))

// Response
// [ [ [Array], [Array] ], [ [Array], [Array] ] ]

These Array bits do actually contain the IDs I'm after, it's just obviously not in the format I'd like...


Solution

  • You can use flatMap to get a simple array instead of an array of arrays :

    const obj = {
      "responseArray":[
        {
          "accounts":[
            {
              "products":[
                {
                  "id":"123",
                }
              ]
            },
            {
              "products":[
                {
                  "id":"456",
                }
              ]
            }
          ]
        },
        {
          "accounts":[
            {
              "products":[
                {
                  "id":"987",
                }
              ]
            },
            {
              "products":[
                {
                  "id":"654",
                }
              ]
            }
          ]
        }
      ]
    }
    
    const mapped = obj.responseArray.flatMap(item => item?.accounts.flatMap(acc => acc.products.map(prod => prod.id)))
    
    console.log(mapped)