Clean way to remove an identical nested object in javascript can you give me some feedback about my approach to remove an idential element from following data structure?
const items = {
  'Sun Mar 07 2021': [
     { id: 2 },
     { id: 1 }
  ],
  'Sat Mar 06 2021': [
     { id: 1 } // remove me
  ]
}

const id = 1 // filter by id 1
const newDate = 'Sun Mar 07 2021' // filter by newDate

let oldDate = ''
// Find the duplicate date and 
// save it in oldDate to splice it afterwards
Object.keys(items).forEach(date =&gt; {
  items[date].forEach(item =&gt; {
    const match = item.id === id
    if (match &amp;&amp; date !== newDate) {
      oldDate = date
    }
  })
})

const idx = items[oldDate].findIndex(el =&gt; el.id === id)
// remove the old item from matched array
if (oldDate) items[oldDate].splice(idx, 1)

I think it can be simplified or solved differently. Unfortunately I can't get any further, do you have any ideas?
I think it can be simplified or solved differently.

That's good intuition. That's called a code smell. Something &quot;smells&quot; funny, off, or wrong but not sure what it is. Pay attention to that feeling!!

Unfortunately I can't get any further

This is an even stronger code smell.

do you have any ideas?


Re-examine the date object design.

date and IDs should be in one object
Put the date objects into an array. Array is designed for easy handling of multiple objects.
Using Array's provided methods should eliminate external variables and functions.




This code demonstrates overall structural changes after fixing the objects. Algorithm details not shown.
const dates = [
  { date : 'Sun Mar 07 2021',
     IDs : [ 1, 2 ]
  },
  { date : 'Sat Mar 06 2021',
     IDs : [ 1 ]
  }
]

const dupeDate = { date : 'Sun Mar 07 2021', IDs : [ 1 ] }

dates.forEach( date =&gt; {

  if( date.date === dupeDate.date ) return;

  if( date.IDs.includes( dupeDate.IDs[0] )) { 
    // algorithm details here. Should be function calls as much as possible, 
    // not dozens of lines of nested, nested code.
  }
});