首页 > 解决方案 > How can I make the ES6 function generic for the whole project?

问题描述

I have a project in Typescript and I have created a function that is responsible for comparing two arrays of objects by a key and removing from the first array those that do not match in the second.

This is my current code:

public async onlyObject() {

        let obj1 = [ 
             { codCountry: 'CO', fileName: 'CO_SER.txt' },
             { codCountry: 'CO', fileName: 'CO_TES.txt' } ];

        let filesSheet = [
             { codCountry: 'CO', fileName: 'CO_SER.txt' },
             { codCountry: 'CO', fileName: 'CO_DAT.txt' } ];

        let onlyObj1 = await this.objectComparer(obj1, obj2);

}

public async  objectComparer(fstArr, secArr) {
      try {
        let only = fstArr.filter(({ fileName: id1 }) => !secArr.some(({ fileName: id2 }) => id2 === id1));
        return Promise.resolve(only);
        
      } catch (error) {
        console.log(error)        
      }  
}

onlyObj1 = [ { codCountry: 'CO', fileName: 'CO_TES.txt' } ];

In this case, it compares the arrays well and filters me by the key fileName. What I want is to make it generic for all objects even if they don't have the same keys. Is that possible? How can I do it?

This is an example of what I want to achieve, passing other different objects with different keys, that the same function returns the same result:

let objN1 = [ 
    { code: '1', country: 'Spain' },
    { code: '2', country: 'Germany' } ];

let objN2 = [ 
    { code: '1', country: 'Italy' },
    { code: '2', country: 'Spain' } ];

onlyObjN1 = [ { code: '2', country: 'Germany' } ]

How can I modify the objectComparer function to pass it the key to filter by? In this case, it should filter by country

标签: javascriptarraystypescriptecmascript-6filter

解决方案


您可以修改objectComparer函数以接受任何键并使用它来比较对象。

public async objectComparer(fstArr, secArr, key) {
  try {
    let only = fstArr.filter(
      (fstItem) => !secArr.some((secItem) => fstItem[key] === secItem[key])
    );
    return Promise.resolve(only);
  } catch (error) {
    console.log(error);
  }
}

推荐阅读