从对象内删除数组项

huangapple go评论71阅读模式
英文:

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: &#39;soccer&#39;
        }, {
          hobby: &#39;dance&#39;
        }]
      },
      {
        id: 2,
        category: [{
          hobby: &#39;soccer&#39;
        }, {
          hobby: &#39;dance&#39;
        }]
      }
    ]
  },
  {
    id: 2,
    documents: [{
        id: 1,
        category: [{
          hobby: &#39;dance&#39;
        }, {
          hobby: &#39;soccer&#39;
        }]
      },
      {
        id: 2,
        category: [{
          hobby: &#39;soccer&#39;
        }, {
          hobby: &#39;dance&#39;
        }]
      }
    ]
  }
];
people.forEach(person =&gt; {
  person.documents.forEach(document =&gt; {
    document.category.forEach((cat, index) =&gt; {
      if (cat.hobby === &#39;dance&#39;) {
        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 =&gt; {
    person.documents.forEach(document =&gt; {
      const catAsSet = new Set(document.category)
      catAsSet.forEach(cat =&gt; { 
        cat.hobby &amp;&amp; 
        cat.hobby === hobby &amp;&amp;
        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.

huangapple
  • 本文由 发表于 2023年4月7日 02:16:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952584.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定