javascript - 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
解决方案
您可以修改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);
}
}
推荐阅读
- swift - 突出文本中的差异
- node.js - 如何在 Alexa ASK SDK V2 中使用 addErrorHandlers
- jquery - 无法使 jQuery ajax 调用持续超过 4 分钟,即使设置了超时,net::ERR_EMPTY_RESPONSE 错误
- sql-server - SQL 从 2 个表中拆分具有相同 ID 的值
- javascript - 如何使用 GraphQL 显示来自道具的图像?可以显示图片网址但不能显示图片本身
- sql-server - 为什么在使用 django-allauth 的初始迁移过程中会出现错误?
- spring-boot - @Autowired 不适用于 CrudRepository
- css - 左/右页依赖格式
- c++ - 将值传递给循环内的数组
- java - gradle wrapper 失败,“无法从 11.0.1 确定 java 版本”对于 android 应用程序