Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your code is almost correct, but there is a slight issue when using forEach to modify an array while iterating it. This can lead to skipping elements or incorrect results. Instead, use the filter method to create a new array with only the elements that don’t match the condition.

people.forEach(person => {
person.documents.forEach(document => {
    document.category = document.category.filter(cat => cat.hobby !== 'dance');
})
});

console.log(people);

This iterates through each person, document, and category using forEach, but instead of directly modifying the category array, it reassigns the category array to a new array with only the elements where the hobby is not ‘dance’. This prevents any issues related to modifying the array while iterating it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading