我们有变量 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] },
]
或
const currentCategoryId = 16
返回
[
{ 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] },
]
答案 0 :(得分:1)
使用Array.prototype.filter()和Array.prototype.includes()函数实现起来应该很简单。
const arr = [
{ 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
const result = arr.filter((arr) => {
return arr.categories.includes(currentCategoryId);
});
console.log(result);
filter()
方法创建一个新数组,其中所有元素都通过了由提供的回调函数实现的测试。
includes()
方法确定数组在其条目中是否包含某个值,并在适当时返回true或false。在此示例中,它检查categoryId
是否包含在当前数组元素的类别字段中。
答案 1 :(得分:0)
不要在内部数组中为类别使用 .filter ,而应使用 .includes 方法来检查categoryId是否存在。使用filter的简单通用解决方案,包括数组方法,传递数组和categoryId。它返回过滤的数据
var array =[
{ id: 18, title: "hello world!", categories: [12, 18] },
{ id: 12, title: "hi hi hi", categories: [12] },
{ id: 65, title: "hi there!", categories: [16] },
]
function filterData(data,categoryId){
return data.filter(obj => obj.categories.includes(categoryId));
}
console.log(filterData(array,12))
console.log(filterData(array,16))
答案 2 :(得分:0)
解决方案#1 :使用数组帮助器(原型).filter()
和.includes()
是返回数据数组中所有元素的数组的最简单方法其中包括您要查找的类别编号:
var data = [
{ id: 18, title: "hello world!", categories: [12, 18] },
{ id: 12, title: "hi hi hi", categories: [12] },
{ id: 65, title: "hi there!", categories: [16] },
];
console.log('searching for items with category 12...');
console.log(data.filter(a => a.categories.includes(12)));
console.log('searching for items with category 16...');
console.log(data.filter(a => a.categories.includes(16)));
解决方案#2 :即使通过从数据数组(使用Object.entries()
返回名称值对的数组来工作,也不要成为单线的家伙/女孩。然后将其简化为数据数组中的一个值数组,该数组仅 包含您想要的类别编号(使用Array.prototype.indexOf()
)。
var data = [
{ id: 18, title: "hello world!", categories: [12, 18] },
{ id: 12, title: "hi hi hi", categories: [12] },
{ id: 65, title: "hi there!", categories: [16] },
];
// Nasty one-liner
const fcbid = (arr, id) => Object.entries(arr).reduce((a,c) => ((c[1].categories.indexOf(id) != -1) && a.push(c[1]), a), []);
console.log('searching 12...');
console.log(fcbid(data, 12));
console.log('searching 16...');
console.log(fcbid(data, 16));