我有两个联系人列表:
Old List:
[{ firstname: "James", nickname: "Jim" }];
New List:
[
{ firstname: "Jim" },
{ firstname: "Jane" }
];
我想创建一个测试,将每个新联系人与现有旧联系人进行比较,以查看是否有匹配。如果FirstName或Nickname Match匹配,则应将联系人视为平等(因此,与firstName" Jim"的新联系应与旧的触点与昵称" Jim"匹配,而不是" Jane"(。
我的第一次尝试很la脚:
let equalFirst = (
( old.firstname === new.firstname ) ||
( old.nickname === new.nickname ) ||
( old.firstname === new.nickname ) ||
( old.nickname === new.firstname )
) ? true : false;
除了不优雅外,这还返回不正确的平等。如果两个联系人的昵称是undefined
,则JavaScript认为它们相等。
只有在测试的值是真实的情况下才能检查平等?使用下划线,我得到了返回正确平等的东西:
let oldNames = _.compact([ old.firstName, old.nickname ]),
newNames = _.compact([ new.firstName, new.nickname ]),
isMatch = _.some( oldNames, ( item ) => {
return _.contains( newNames, item );
});
但是,我觉得可能有一种更好的方法来执行此操作,因此undefined
值被排除在外,并且仅评估真相值。
添加真实的验证。
let equalFirst = (
( new.firstname && old.firstname === new.firstname ) ||
( new.nickname && old.nickname === new.nickname ) ||
( new.nickname && old.firstname === new.nickname ) ||
( new.firstname && old.nickname === new.firstname )
) ? true : false;
您可以取一组所有名称并检查结果的集合。
var oldList = [{ firstname: "James", nickname: "Jim" }],
newList = [{ firstname: "Jim" }, { firstname: "Jane" }],
oldSet = new Set(
oldList
.reduce((r, { firstname, nickname }) => r.concat(firstname, nickname), [])
.filter(Boolean) // removes undefined or empty names
),
result = newList.map(
({ firstname, nickname }) => [firstname, nickname].some(v => oldSet.has(v))
);
console.log(result);
console.log([...oldSet]);