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

Format nested array of objects in typescript

I have the below sample array of objects

let arr = [{id: 1,name: 'Test',segment: 'test',subCategory: [{id: 1,name:'Test1',segment:'test1'}]}]

I need to format this array to the below structure

let newArr = [{link: 'test', name: 'Test',subCategory: [{link: 'test1',name: 'Test1'}]}]

How to do this in an easy step in typescript?

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 simply use Map method to achieve your desired result:

let arr = [
  { id: 1, name: 'Test', segment: 'test', subCategory: [{ id: 1, name: 
'Test1', segment: 'test1' }] }
];

let newArr = arr.map(item => {
  return {
    link: item.segment,
    name: item.name,
    subCategory: item.subCategory.map(subItem => {
      return {
        link: subItem.segment,
        name: subItem.name
      };
    })
 };
});

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