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 array from javascript object

I have below javascript object – (named Division)
I want to extract only SubDivs from the array

I tried : –

const division = [{
    Name: "DivName1",
    Value: "DivValue1",
    SubDivision: {
      Name: "SubDiv1",
      Value: "SubDiv1"
    }
  },
  {
    Name: "DivName2",
    Value: "DivValue2",
    SubDivision: [{
        Name: "SubDiv2",
        Value: "SubDiv2"
      },
      {
        Name: "SubDiv3",
        Value: "SubDiv3"
      }
    ]
  }
]



var subDivs = division.map(x => x.SubDivision);
console.log(subDivs)

But this is not giving me array in format –

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

[{
Name:"SubDiv1",
Value:"SubDiv1"
},
{
Name:"SubDiv2",
Value:"SubDiv2"
},
{
Name:"SubDiv3",
Value:"SubDiv3"
}]

>Solution :

You can use flatMap for that

const division = [{
    Name: "DivName1",
    Value: "DivValue1",
    SubDivision: [{
      Name: "SubDiv1",
      Value: "SubDiv1"
    }]
  },
  {
    Name: "DivName2",
    Value: "DivValue2",
    SubDivision: [{
        Name: "SubDiv2",
        Value: "SubDiv2"
      },
      {
        Name: "SubDiv3",
        Value: "SubDiv3"
      }
    ]
  }
]

const subdivision = division.flatMap(d => d.SubDivision)

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