繁体   English   中英

比较两个对象数组并获得差异

[英]compare two array of objects and get difference

嘲笑

a = [{id:123},{id:1234},{id:12345}]
b = [{id:123},{id:1234},{id:123456}]

代码

a.filter((element)=> {
  return b.some((ele) =>{
    if (element.id === ele.id) {
     return matched[element.id] = element.id
    } else {
      return unmatched[element.id] = element.id
    }
 });
});

预期 output

matched = {123: 123, 1234: 1234}
unmatched = {12345: 12345}

output

unmatched = {123: 123, 1234: 1234, 12345: 12345}
matched = {123: 123, 1234: 1234}

任何人都可以在这里帮助我。 我正在尝试比较两个 arrays 并将差异转化为不同的对象

您可以将Set或 object 用于a并迭代b以获得正确的 object。

 const a = [{ id: 123 }, { id: 1234 }, { id: 12345 }], b = [{ id: 123 }, { id: 1234 }, { id: 123456 }], aSet = new Set(a.map(({ id }) => id)), [matched, unmatched] = b.reduce((r, { id }) => { Object.assign(r[1 - aSet.has(id)], { [id]: id }); return r; }, [{}, {}]); console.log(matched); console.log(unmatched);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

直接使用对象的方法

 const a = [{ _id: '123', index: 3 }, { _id: '1234', index: 3 }], b = [{ _id: '123', index: 2 }, { _id: '12345', index: 3 }], aSet = new Set(a.map(({ _id }) => _id)), [matched, unmatched] = b.reduce((r, o) => { r[1 - aSet.has(o._id)].push(o); return r; }, [[], []]); console.log(matched); console.log(unmatched);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

这会起作用:

a = [{id:123},{id:1234},{id:12345}];
b = [{id:123},{id:1234},{id:123456}];

function compare(a, b) {
    const returnObj = { matched: [], unmatched: [] };
    a.forEach(aItem => {
        const found = b.find(bItem => JSON.stringify(aItem) === JSON.stringify(bItem));
        returnObj[found ? 'matched' : 'unmatched'].push(aItem);
    });
    return returnObj;
}

const { matched, unmatched } = compare(a, b);

console.log(matched);
console.log(unmatched);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM