Typescript过滤两个对象数组

时间:2019-10-10 21:37:54

标签: javascript typescript angular-filters

我必须对象需要过滤掉其中一个而不是另一个的数据

例如对象1

0:Object {Name: "Java", ResourceCount: 3}
1:Object {Name: "DotNet", ResourceCount: 4}
2:Object {Name: "Hadoop", ResourceCount: 1}
3:Object {Name: "Pega", ResourceCount: 2}
4:Object {Name: "Oracle", ResourceCount: 1}
5:Object {Name: "ETL", ResourceCount: 1}

对象2

0:"DotNet"
1:"ETL"
2:"Hadoop"
3:"Java"
4:"Oracle"
5:"Pega"
6:"Mainframe"

我需要从对象2返回“ MainFrame”,因为它在对象1中不存在。

到目前为止,这是我一直尝试的尝试。

  const filteredList = object2.filter(item1 => 
          object1.find(item2 => item1.Name != item2.Name));

这一切都是返回对象2中的所有行

1 个答案:

答案 0 :(得分:1)

基本上,创建一个名称数组来帮助过滤对象2; (array2) 如果存在多个名称,则我将结果与添加在一起

let object1 = [{Name: "Java", ResourceCount: 3}, {Name: "DotNet", ResourceCount: 4}, {Name: "Hadoop", ResourceCount: 1}, {Name: "Pega", ResourceCount: 2}, {Name: "Oracle", ResourceCount: 1}, {Name: "ETL", ResourceCount: 1}]
let object2 = ["DotNet", "ETL", "Hadoop", "Java", "Oracle", "Pega", "Mainframe"]

let object1Names = object1.map(obj => obj.Name); // for caching the result
results = object2.filter(name => !object1Names.includes(name)).join(',');
console.log(results);