我检查用于把嵌有以下代码另一阵列中的阵列上平等:
const equal = take("services", compare(
take("history", compare(
(a, b) => a._id === b._id
))
))(obj, obj2);
这是在比较,看起来像这样两个文件:
const obj = {
_id: 1,
services: [
{
_id: 23,
service: "serviceOne",
history: [
{
_id: 33,
stage: "stageOne"
}
]
},
{
_id: 24,
service: "serviceTwo",
history: [
{
_id: 44,
stage: "stageOne"
}
]
},
]
};
const obj2 = {
_id: 1,
services: [
{
_id: 23,
service: "serviceOne",
history: [
{
_id: 33,
stage: "stageOne"
}
]
},
{
_id: 24,
service: "serviceTwo",
history: [
{
_id: 45,
stage: "stageTwo"
},
{
_id: 44,
stage: "stageOne"
}
]
},
]
};
上述工作。当我运行console.log('equal: ', equal)
它记录false
,因为在history
阵列的级别内的差异。
我现在要做的就是挖掘出价值“services.service”里的两个文件之间存在的差异。到目前为止,我已经试过只得到我要“history.stage”的值:
const compare = cb => (a, b) => a.length === b.length && a.every((el, i) => cb(el, b[i]));
const take = (key, cb) => (a, b) => cb(a[key], b[key]);
const obj = {
_id: 1,
services: [{
_id: 23,
service: "serviceOne",
history: [{
_id: 33,
stage: "stageOne"
}]
},
{
_id: 24,
service: "serviceTwo",
history: [{
_id: 44,
stage: "stageOne"
}]
},
]
};
const obj2 = {
_id: 1,
services: [{
_id: 23,
service: "serviceOne",
history: [{
_id: 33,
stage: "stageOne"
}]
},
{
_id: 24,
service: "serviceTwo",
history: [{
_id: 45,
stage: "stageTwo"
},
{
_id: 44,
stage: "stageOne"
}
]
},
]
};
const targetService = take("services", compare(
take("history", compare(
(a, b) => {
a._id === b._id;
console.log(a);
}
))
))(obj, obj2);
console.log(targetService);
我怎么会在这种情况下得到“services.service”?基于在这里我的文档,我想回到serviceTwo
,因为它是一个的改变了这一切元素中的history
阵列。
如果你想保持功能性的模式,你可能要添加一个and
帮手,让您进行多重比较:
const compare = cb => (a, b) => a.length === b.length && a.every((el, i) => cb(el, b[i]));
const take = (key, cb) => (a, b) => cb(a[key], b[key]);
const and = (cb1, cb2) => (a, b) => cb1(a, b) && cb2(a, b);
const equals = (a, b) => a === b;
const equal = take("services", compare(
and(
take("service", equals),
take("history", compare(
take("_id", equals)
))
)
))(obj, obj2);
但是,如果你跳过功能编程的东西,使它有点更容易阅读可能更容易:
const historyEquals = (a, b) =>
a._id === b._id;
const serviceEquals = (a, b) =>
a.service === b.service &&
a.history.length === b.history.length &&
a.history.every((el, i) => historyEquals(el, b.history[i]));
const objEquals = (a, b) =>
a.services.length === b.services.length &&
a.services.every((el, i) => serviceEquals(el, b.services[i]));