首页 > 解决方案 > 当这些 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 中有类似的东西?

标签: javascriptvue.jsnuxt.js

解决方案


您可以在第二个数组上使用 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))

推荐阅读