【发布时间】:2019-09-23 06:53:15
【问题描述】:
我有一个 Array 或 Objects。
每个Objects数组都包含一个数组items,这个数组中的每一项都是一个Object,其中包含一个数组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'],则数组应该包含category包含['E','M']的任何对象(无论category是否为['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.
[UPDATE] 我添加了一个更真实的数据样本,很抱歉之前没有提供它:https://drive.google.com/open?id=1sdRx6sQ-cnRXJ8YCe4QH2Sy5fa5mopYW
【问题讨论】:
-
结果应该如何?你想要只有嵌套想要类别的对象吗?变异的还是新的?
-
@NinaScholz:生成的数组 obj 必须具有当前结构,但如果一个对象中的一个类别与用户偏好不匹配,则应将其从项目中删除(例如,如果用户发送['M'],必须删除 id=2 的项目)。无论如何,我更喜欢新数组。
-
obj.map(obj => obj.items.filter(item => data.every(c => item.category.includes(c))));
标签: javascript filter