我有一个对象数组
。
每个对象数组包含一个items
数组,该数组中的每个项都是一个包含category
数组的对象:
var obj = [
// first object
{
label: 'Label 1',
// first items
items: [
{
id: 1,
itemName: 'Item Name 1',
img: 'imgs/path-to1.jpeg',
sizes: [],
colors: [],
// first category
category: [
'I',
'E',
'M'
],
defaultChoices: {}
},
{
id: 2,
itemName: 'Item Name 2',
img: 'imgs/path-to2.jpeg',
sizes: [],
colors: [],
// second category
category: [
'I',
'E'
],
defaultChoices: {}
},
{
id: 3,
itemName: 'Item Name 3',
img: 'imgs/path-to3.jpeg',
sizes: [],
colors: [],
// third category
category: [
'I'
],
defaultChoices: {}
},
]
},
// second object
{
label: 'Label 2',
// second items
items: [
{
id: 7,
itemName: 'Item Name 7',
img: 'imgs/path-to7.jpeg',
sizes: [],
colors: [],
// fourth category
category: [
'I',
'M'
],
defaultChoices: {}
},
...
为了更清楚地说明,典型的直接访问category
的方法是这样进行的:obj[0].items[0].category
。
从应用程序的前端,用户可以根据自己的选择向应用程序发送以下其中之一的数组:
['I']
;['E']
;['M']
;['I','E']
;['I','M']
;['E','M']
;['I','E','M']
;- ...;
然后,应用程序应该返回过滤后的obj
数组:例如,如果用户发送了['I']
,则数组应该包含任何类别包含“I”的对象。如果用户发送了['E','M']
,则数组应该包含任何类别包含['E','M']
的对象(无论类别是否为['E','M','I']
),等等。
我阅读了很多关于JS filter
函数的文档,但我无法开发一个函数,可以根据用户数组返回过滤obj
的新数组作为结果。我找到了数十篇非真实生活示例的文档,例如这一个:
var hs = [
{name: 'Batman', franchise: 'DC'},
{name: 'Ironman', franchise: 'Marvel'}
];
var marvels = heroes.filter(function(h) {
return hs.franchise == 'Marvel';
});
Any help is appreciated.
[更新] 我添加了一个更加真实的数据样本,之前没有提供很抱歉:https://drive.google.com/open?id=1sdRx6sQ-cnRXJ8YCe4QH2Sy5fa5mopYW。