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

Combine All Array Inside of Arrays

I have a problem on combining arrays that I wanted to get that’s coming from another array.

datas

   datas = [
      {
        "id": "22333",
        "name": "",
        "details": [
          {
            "value": 1
          },
          {
            "value": 2
          }
        ]
      },
      {
        "id": "4444",
        "name": "",
        "details": [
          {
            "value": 99
          },
          {
            "value": 66
          }
        ]
      }
    ]

expected output

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

final = [
    {
      "value": 1
    },
    {
      "value": 2
    },
    {
        "value": 99
    },
    {
        "value": 66
    }
  ]

Code

  datas.map((data) => ({ ...data.details}))

>Solution :

Replace map with flatMap.

The flatMap method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map followed by a flat of depth 1, but slightly more efficient than calling those two methods separately.

const datas=[{id:"22333",name:"",details:[{value:1},{value:2}]},{id:"4444",name:"",details:[{value:99},{value:66}]}];
    
const flattened = datas.flatMap(obj => obj.details);

console.log(flattened);
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