Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading