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

add new array into an array from its array's subarray

I have an array,

let arr =[{SLNO:1, modules:[{id:1, name:DTR},{id:5, name:DYR},{id:8, name:YUR}]},
          {SLNO:2, modules:[{id:6, name:DTTR},{id:9, name:TTDYR}]}]

I want to add a new array into this array with modules IDs like,

let newarr =[{SLNO:1, modules:[{id:1, name:DTR},{id:5, name:DYR},{id:8, name:YUR}], mIDS:[1,5,8]},
          {SLNO:2, modules:[{id:6, name:DTTR},{id:9, name:TTDYR}],  mIDS:[6,9]}]

How to write like this?

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 the forEach (documentation) and the map (documentation) methods

const arr = [{
    SLNO: 1,
    modules: [
       {id: 1,name: "DTR"},
       {id: 5, name: "DYR"},
       {id: 8,name: "YUR"}
    ]
  },
  {
    SLNO: 2,
    modules: [
       {id: 6,name: "DTTR"},
       {id: 9,name: "TTDYR"}
    ]
  }
]

arr.forEach(item => {
  const ids = item.modules.map(x => x.id)
  item.mIDS = ids
})

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