javascript - 当这些 id 在 JavaScript 中的另一个数组中时,如何根据它们的 id 删除对象
问题描述
我来有两个不同的数组。一个仅包含 id 作为整数(来自搜索框),另一个包含对象,例如:
categories = [1, 2, 5, 8];
items = [
{ title: 'Hello', description: 'whatever you want to be a description', categoryId: 1 },
{ title: 'Hello', description: 'whatever you want to be a description', categoryId: 3 }
]
我一直在寻找一种方法来删除第二个数组中的任何项目,如果它的 categoryId 等于类别数组中存在的任何值。
起初我尝试拼接,循环进入它们(并因此创建了某种无限循环),寻找 indexOf ......要么我做得不好,要么使用了错误的方法,但是现在三天,什么都没有做。
JS 中是否有任何方法可以返回一个新数组,例如items.splice(every.categories)
(我知道这个不存在,但谁知道......在 ES6 中有类似的东西?
解决方案
您可以在第二个数组上使用 filter 方法并检查 categoryId 是否存在于第一个数组中
const categories = [1, 2, 5, 8];
const items = [ { title: 'Hello', description: 'whatever you want to be a description', categoryId: 1 }, { title: 'Hello', description: 'whatever you want to be a description', categoryId: 3 } ]
const result = items.filter(item => !categories.find(cat => cat === item.categoryId))
推荐阅读
- java - JSON 有效负载的 Java 验证:以树的形式返回错误
- awk - awk/sed 删除重复并合并排列的列
- excel - ActiveSheet.PasteSpecial 有效,Transpose:=True 出错
- c# - 使用 c# 将文件上传到谷歌云存储
- excel - MindManager 不会显示 Excel 范围
- git - 重命名包含(本地)git 存储库的复制文件夹会导致 git 按预期停止工作吗?
- mongodb - 聚合匹配 $expr 与 $divide $mod 和 $floor 的组合不起作用
- redis - Redis占用更多内存
- r - 无边界的 R 序列生成
- jquery - 我想在 wordpress 中悬停时更改 img 的 url