我正在尝试过滤一些事件及其相应的时间段。数据结构如下:
var items = [
{
title: 'Category Title',
events: [
{
title : '1:00pm',
category : 1
},
{
title: '2:00pm',
category : 2
}
]
},
{
title: 'Category Title 2',
events: [
{
title : '3:00pm',
category : 1
},
{
title: '4:00pm',
category : 2
}
]
}
];
我想按类别过滤事件。我尝试过使用过滤器/ map ,但似乎无法弄清楚。例如,如何过滤列表以仅返回类别为 1 的项目?
最佳答案
您可以使用函数 filter
和函数 some
来获取数组 events
中具有特定类别的项目。
此示例有一个项目,其事件数组包含 category === 3
var items = [ { title: 'Category Title', events: [ { title : '1:00pm', category : 1 }, { title: '2:00pm', category : 2 } ] }, { title: 'Category Title 2', events: [ { title : '3:00pm', category : 1 }, { title: '4:00pm', category : 2 } ] }, { title: 'Category Title 3', events: [ { title : '3:00pm', category : 1 }, { title: '4:00pm', category : 3 } ] }],
cat = 3,
result = items.filter(o => o.events.some(({category}) => cat === category));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
如果您只需要获取category === 3
的事件,请使用函数reduce
:
var items = [ { title: 'Category Title', events: [ { title : '1:00pm', category : 1 }, { title: '2:00pm', category : 2 } ] }, { title: 'Category Title 2', events: [ { title : '3:00pm', category : 1 }, { title: '4:00pm', category : 2 } ] }, { title: 'Category Title 3', events: [ { title : '3:00pm', category : 1 }, { title: '4:00pm', category : 3 } ] }],
cat = 3,
result = items.reduce((a/*Accumulator*/, o/*Current object in array*/) => {
// 1. We get the events with a specific category (In this case -> 3)
var filtered = o.events.filter(({category}) => cat === category);
// 2. If the previous filter returns at least one event, we need to push
// the current object 'o' with the filtered events.
if (filtered.length) { // if length !== 0 we need to push the object.
// 3. We use Object.assign to avoid any mutation over the original object.
// So, basically we create a new object with the original properties
// and finally we assign the filtered events to the property events.
a.push(Object.assign({}, o, {events: filtered}));
}
return a;
}, []/*Initial value (this array will contain the filtered objects)*/);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 过滤JS多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49763276/