【发布时间】:2021-09-16 21:46:49
【问题描述】:
假设我有这些对象数组
selectedNames = [
{label: 'Nicolas', value:'Nicolas'},
{label: 'Michael', value:'Michael'},
{label: 'Sean', value:'Sean'},
{label: 'George', value:'George'}
]
selectedWhatever = [
{label: 'Guitar', value: 'Guitar'},
{label: 'Bass', value: 'Bass'}
]
然后是另一个像这样的对象数组:
list = [
{name: 'Nicolas', surname: 'Smith', birthplace: 'NewYork', whatever: 'Guitar'},
{name: 'Sean', surname: 'Narci', birthplace: 'LA', whatever: 'Bass'},
{name: 'George', surname: 'Rossi', birthplace: 'NewYork', whatever: 'Bass'},
{name: 'Fiona', surname: 'Gallagher', birthplace: 'Madrid', whatever: 'Drum'},
{name: 'Michael', surname: 'Red', birthplace: 'London', whatever: 'Triangle'},
]
我想根据我在其他两个数组中的数据过滤 list 并按出生地分组,所以我想要这个:
result = {
LA: [
{name: 'Sean', surname: 'Narci', birthplace: 'LA', whatever: 'Bass'},
],
NewYork: [
{name: 'Nicolas', surname: 'Smith', birthplace: 'NewYork', whatever: 'Guitar'},
{name: 'George', surname: 'Rossi', birthplace: 'NewYork', whatever: 'Bass'},
]
}
我所做的是以下,它工作正常。有没有更聪明或更优雅的方法来做同样的事情?
const obj = {};
list.map((res) => {
if ((data.selectedNames.map((r) => r.label).includes(res.name))
&& (data.selectedWhatever.map((r) => r.label).includes(res.whatever))
){
result[res.birthplace] = result[res.birthplace] ?? []:
result[res.birthplace].push(res);
}
})
【问题讨论】:
-
使用
list.forEach代替list.map,使用data.selectedNames.filte(r => r.label === res.name)r代替data.selectedNames.map((r) => r.label).includes(res.name))(data.selectedWhatever.map((r) => r.label).includes(res.whatever)的更改相同)
标签: javascript arrays object filter null-coalescing