Search code examples
javascriptarraystypescriptobjectsplice

Delete item from array inside objects


How to delete items from an array inside objects.

It should remove all the hobbies that are dance. I tried to use splice.

const people = [{
    id: 1,
    documents: [{
        id: 1,
        category: [{
          hobby: 'soccer'
        }, {
          hobby: 'dance'
        }]
      },
      {
        id: 2,
        category: [{
          hobby: 'soccer'
        }, {
          hobby: 'dance'
        }]
      }
    ]
  },
  {
    id: 2,
    documents: [{
        id: 1,
        category: [{
          hobby: 'dance'
        }, {
          hobby: 'soccer'
        }]
      },
      {
        id: 2,
        category: [{
          hobby: 'soccer'
        }, {
          hobby: 'dance'
        }]
      }
    ]
  }
];
people.forEach(person => {
  person.documents.forEach(document => {
    document.category.forEach((cat, index) => {
      if (cat.hobby === 'dance') {
        document.category.splice(index, 1)
      }
    })
  })
})

console.log(people);


Solution

  • Not necessary at all, but I've personally liked sets for this sort of task:

    function deleteHobbyFrom(people, hobby) {
      people.forEach(person => {
        person.documents.forEach(document => {
          const catAsSet = new Set(document.category)
          catAsSet.forEach(cat => { 
            cat.hobby && 
            cat.hobby === hobby &&
            catAsSet.delete(cat)
           })
          document.category = Array.from(catAsSet)
        })
      })
    }
    
    

    I don't think I'd normally convert from array to set back to array like I did here but could be worth considering using Set as your data structure instead of an Array.