Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在对象有另一个数组的情况下过滤对象数组?_Javascript - Fatal编程技术网

Javascript 如何在对象有另一个数组的情况下过滤对象数组?

Javascript 如何在对象有另一个数组的情况下过滤对象数组?,javascript,Javascript,我们有变量currentCategoryId和对象数组 [ { id: 18, title: "hello world!", categories: [12, 18] }, { id: 12, title: "hi hi hi", categories: [12] }, { id: 65, title: "hi there!", categories: [16] }, ] 例如const currentCate

我们有变量currentCategoryId和对象数组

[
    { id: 18, title: "hello world!", categories: [12, 18] },
    { id: 12, title: "hi hi hi", categories: [12] },
    { id: 65, title: "hi there!", categories: [16] },
]
例如
const currentCategoryId=12
,需要返回新的过滤器数组

[
    { id: 18, title: "hello world!", categories: [12, 18] },
    { id: 12, title: "hi hi hi", categories: [12] },
]

返回

[
    { id: 65, title: "hi there!", categories: [16] },
]
我的代码

 const postsByCategory = posts.filter(({ categories }) =>
    categories.filter(
      categoryId => categoryId === 
       currentCategoryId
    )
)
返回

[
    { id: 18, title: "hello world!", categories: [12, 18] },
    { id: 12, title: "hi hi hi", categories: [12] },
    { id: 65, title: "hi there!", categories: [16] },
]

不要在类别的内部数组中使用.filter,而应该使用.includes方法检查categoryId是否存在。使用过滤器的简单通用解决方案,包括数组方法、传递数组和categoryId。它返回过滤后的数据

var数组=[
{id:18,标题:“你好,世界!”,类别:[12,18]},
{id:12,标题:“你好”,类别:[12]},
{id:65,标题:“你好!”,类别:[16]},
]
函数过滤器数据(数据,类别ID){
返回data.filter(obj=>obj.categories.includes(categoryId));
}
console.log(filterData(数组,12))

log(filterData(array,16))
这应该很容易通过和函数实现

const arr=[
{id:18,标题:“你好,世界!”,类别:[12,18]},
{id:12,标题:“你好”,类别:[12]},
{id:65,标题:“你好!”,类别:[16]},
];
常数currentCategoryId=12
常量结果=arr.filter((arr)=>{
返回arr.categories.包括(currentCategoryId);
});
控制台日志(结果)
解决方案#1:使用数组帮助程序(原型)
.filter()
.includes()
是返回数据数组中所有元素的数组的最简单、最简单的方法,其中包括您要查找的元素和类别号:

var数据=[
{id:18,标题:“你好,世界!”,类别:[12,18]},
{id:12,标题:“你好”,类别:[12]},
{id:65,标题:“你好!”,类别:[16]},
];
log('search for items with category 12…');
log(data.filter(a=>a.categories.includes(12));
log('search for items with category 16…');

log(data.filter(a=>a.categories.includes(16))[ { id: 18, title: "hello world!", categories: [12, 18] }, { id: 12, title: "hi hi hi", categories: [12] }, { id: 65, title: "hi there!", categories: [16] }, ]