typescript 从对象数组中筛选对象[已关闭]

ndh0cuux  于 2023-01-27  发布在  TypeScript
关注(0)|答案(1)|浏览(108)

已关闭。此问题需要超过focused。当前不接受答案。
**想要改进此问题吗?**更新此问题,使其仅关注editing this post的一个问题。

2天前关闭。
Improve this question
我有一个对象数组

[
  { "name":"abc", serviceTags:[{"service":"ddd323"},{"service":"ddd323"},{"service":"ddd323"}]},
  { "name":"addbc", serviceTags:[{"service":"ddd2344"},{"service":"ddd323"},{"service":"ddd323"}]}, 
  { "name":"eeabc", serviceTags:[{"service":"ddd123"},{"service":"ddd323"},{"service":"dddf323"}]},  
]

filterData = ["ddd123","dddf323"]

如何在javascript中基于filterData过滤对象的数组

[
  { "name":"abc", serviceTags:[{"service":"ddd123"}]},
  { "name":"eeabc", serviceTags:[{"service":"dddf323"}]},
]
6jjcrrmo

6jjcrrmo1#

const data = [
    { "name":"abc", serviceTags:[{"service":"ddd323"},{"service":"ddd323"},{"service":"ddd323"}]},
    { "name":"addbc", serviceTags:[{"service":"ddd2344"},{"service":"ddd323"},{"service":"ddd323"}]}, 
    { "name":"eeabc", serviceTags:[{"service":"ddd123"},{"service":"ddd323"},{"service":"dddf323"}]},  
  ];
  
  const requiredServices = ["ddd323", "ddd123"];
  
  const filteredData = data.filter(item => {
    return requiredServices.includes(item.serviceTags[0].service)
  });
  
  const result = filteredData.map(item => {
    const { service } = item.serviceTags[0];
    return {
      name: item.name,
      serviceTags: { service }
    }
  });
  console.log(result);

相关问题