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?
CodePudding user response:
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)
CodePudding user response:
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)