Home > Enterprise >  Remove specific element in nested array in javascript
Remove specific element in nested array in javascript

Time:09-06

I have the following structure. And I am trying to remove specific element in small_caterogy which is in deleteTargetCodeArr

const parentArr = [
  {
    middle_code: "EX42",
        middle_name: "Checkup A",
        small_category:[{name: 'HAV Ab IgG', code: 'CH187'},{name: 'HAV Ab IgM', code: 'CH188'}] 
},
  {
    middle_code: "EX42",
        middle_name: "Checkup B",
        small_categor:[{name: 'HAV Ab IgG', code: 'CH194'},{name: 'HAV Ab IgM', code: 'CH200'}, {name: 'HAV Ab IgM', code: 'CH201'}] 
},
  
  ]
  
const deleteTargetCodeArr =['CH187', 'CH200'] 

So result should be looks like below

[
  {
    middle_code: "EX42",
        middle_name: "Checkup A",
        small_category:[{name: 'HAV Ab IgM', code: 'CH188'}] 
},
  {
    middle_code: "EX42",
        middle_name: "Checkup B",
        small_categor:[{name: 'HAV Ab IgG', code: 'CH194'}, {name: 'HAV Ab IgM', code: 'CH201'}] 
},

  ]

And I found wonderful solutions in this link (JS: Remove object from nested array and return parent array)

I tried this below and perfectly works well for me.

const resultArr = parentArr

resultArr.forEach((item)=> item. small_category.forEach((small, index1)=>{
  if(deleteTargetCodeArr.includes(small.code)){
    return item. small_category.splice(index1,1)
  }
}))

I am wondering is there any efficient way to fix this. Because I checked few article they say it is better to use map, filter or something like these method for efficiency. and it is dangerous using forEach cause this change original data. Also I am not sure is this right use duplicated iterator statements..

If have better ideas please share with me thank you :) ☺️

  • Related