Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
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?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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)

You can also do it using the Array#Map function. It has the benefits to not modify the existing array and generate a new one.

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"}
    ]
  }
]

const newArr = arr.map(item => ({...item, mIDS: item.modules.map(x => x.id)}))

console.log(newArr)

about 4 years ago · Santiago Trujillo Report

0

You can achieve this by using map

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'
    }]
  }
]
arr.map((item) => {
  item.mIDS = item.modules.map((item) => item.id)
  return item
})
console.log(arr)

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!