gpt4 book ai didi

javascript - 根据多个唯一值进行过滤

转载 作者:行者123 更新时间:2023-12-03 08:26:08 25 4
gpt4 key购买 nike

我正在尝试确定以下问题的最佳方法。

我有两个数组,如下所示:

const a = [
{
Employee: "00001",
Seq: "01",
ReportDate: "2021-03-10T00:00:00.000",
ReportName: "test report",
},
{
Employee: "00002",
Seq: "01",
ReportDate: "2020-03-10T00:00:00.000",
ReportName: "test report 2",
},
];


const b = [
{
Employee: "00001",
EmplName: "William Apple",
ReportDate: "2021-03-10T00:00:00.000",
ReportName: "test report",
Posted: "Y",
Seq: "01",
},
{
Employee: "00003",
EmplName: "John Smith",
ReportDate: "2021-03-10T00:00:00.000",
ReportName: "test report 3",
Posted: "Y",
Seq: "01",
},
];

我想过滤掉数组“b”中不包含数组“a”中某个对象中所有 4 个精确值的任何内容。

所以,按照上面的例子,我会留下:

// from array 'b'
const c = [
{
Employee: "00001",
EmplName: "William Apple",
ReportDate: "2021-03-10T00:00:00.000",
ReportName: "test report",
Posted: "Y",
Seq: "01",
}
];

我研究了各种方法来做到这一点。我不能只是检查对象是否相等,因为数组“a”仅包含 4 个值/键,而数组“b”将包含更多/动态数量。

通过循环和多个 IF 语句使用 Filter 方法是最好的方法吗?

最佳答案

我会将精确对象匹配的测试与循环代码分开,如下所示:

const subObject = (a, b) => 
Object .entries (a) .every (([k, v]) => b [k] == v)

const matches = (xs, ys) =>
ys .filter (y => xs .some (x => subObject (x, y)))

const a = [{Employee: "00001", Seq: "01", ReportDate: "2021-03-10T00:00:00.000", ReportName: "test report"}, {Employee: "00002", Seq: "01", ReportDate: "2020-03-10T00:00:00.000", ReportName: "test report 2"}]
const b = [{Employee: "00001", EmplName: "William Apple", ReportDate: "2021-03-10T00:00:00.000", ReportName: "test report", Posted: "Y", Seq: "01"}, {Employee: "00003", EmplName: "John Smith", ReportDate: "2021-03-10T00:00:00.000", ReportName: "test report 3", Posted: "Y", Seq: "01"}]

console .log (matches (a, b))

subObject 检查a 的每个属性在b 中是否具有相同的值。

matches 使用它根据第一个列表是否具有作为其子对象的某个元素来过滤第二个列表。

这两个函数都非常简单。虽然我们可以在 matches 中内联 subObject,但我认为它本身很有用,并且可以生成像这样更好的代码。

关于javascript - 根据多个唯一值进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66571173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com