英文:
Delete item from array inside objects
问题
const people = [{
    id: 1,
    documents: [{
        id: 1,
        category: [{
          hobby: 'soccer'
        }]
      },
      {
        id: 2,
        category: [{
          hobby: 'soccer'
        }]
      }
    ]
  },
  {
    id: 2,
    documents: [{
        id: 1,
        category: [{
          hobby: 'soccer'
        }]
      },
      {
        id: 2,
        category: [{
          hobby: 'soccer'
        }]
      }
    ]
  }
];
console.log(people);
英文:
How to delete items from an array inside objects.
It should remove all the hobbies that are dance.
I tried to use splice.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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);
<!-- end snippet -->
答案1
得分: 0
根本没有必要,但我个人喜欢用集合来完成这样的任务:
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)
})
})
}
我不认为我会像我在这里做的那样通常将数组转换为集合,但考虑使用集合作为数据结构可能是值得考虑的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论