【问题标题】:Check if an a propery of an object from an array is contained in another array of object检查数组中对象的属性是否包含在另一个对象数组中
【发布时间】: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


【解决方案1】:

与其为每个检查的条目创建和搜索一个新的名称数组和其他任何内容,不如只创建一次并将它们与他检查的密钥一起存储为集合:

 const filters = {
    name: new Set( selectedNames.map(it => it.label) )
 };

 const result = list.filter(it => 
    Object.entries(filters).some(([key, set]) =>
        set.has( it[key] )
     )
  );

分组部分也应该是一个可重用的函数。

【讨论】:

    猜你喜欢
    • 2021-12-26
    • 2016-04-24
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    相关资源
    最近更新 更多