我正在尝试确定以下最佳方法。
我有两个数组,如下所示:
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
用于根据第一个列表是否具有某个元素作为其子对象来过滤第二个列表。
两者都证明是非常简单的功能。虽然我们可以内联subObject
到内部matches
,但我认为它本身很有用,并且可以生成更好的代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句