【问题标题】:How to merge two arrays of objects, filtering out matching ID's and merging objects with matching ID's seperately如何合并两个对象数组,过滤掉匹配的 ID 并分别合并具有匹配 ID 的对象
【发布时间】:2022-11-24 20:17:16
【问题描述】:

我需要组合两个对象数组:

const local: [
    {id: 1, balance: 2200, ref: 'A'},
    {id: 2, balance: 2100, ref: 'C'}
]
const remote: [
    {id: 1, balance: 3300, ref: 'B'},
]

我需要合并这些数组,这样任何两个具有相同 ID 的对象都会被合并 - 保持相同的 ID,保持 remote 的余额并合并它们的 ref 值,所以这个例子的理想输出是:

  [
       { id: 1, balance: 3300, text: 'A / B' },
       { id: 2, balance: 2100, text: 'C' }
  ]

我该怎么做?我试过以下方法:

function mergeFunc(remoteArray, localArray) {
    const newArray = [];
    //loop over one of the arrays
    for (const localObj of localArray) {
        //for each iteration, search for object with matching id in other array
        if(remoteArray.some(remoteObj => remoteObj.id === localObj.id)){
            //if found matching id, fetch this other object
            const id:matchingRemoteObj = remoteArray.find(item => item.id === localObj.id);
            //create new, merged, object
            const newObj = {id:matchingRemoteObj.id, balance: id:matchingRemoteObj.balance, text:`${localObj.text} / ${id:matchingRemoteObj.text}`}
            //push new value to array
            newArray.push(newObj);
        }
    }
    return newArray;
}

问题是,此解决方案为我提供了一组具有匹配 ID 的合并对象。我需要一个数组全部对象,只合并具有匹配 id 的对象...

【问题讨论】:

  • remote 可以拥有 ID 不在 local 中的对象吗?如果是这样,这些对象是否应该包含在输出中?
  • @NickParsons 是的,远程和本地是独立的数组,偶尔需要“同步”并合并。合并后的输出应该包含来自两个数组的所有唯一对象,以及 id 匹配的合并对象......

标签: javascript arrays json object


【解决方案1】:

原因在下面的代码中,你只是推送匹配记录,导致这个问题

if(remoteArray.some(remoteObj => remoteObj.id === localObj.id))

以下是使用Array.map()Array.find()供您参考

const local = [
    {id: 1, balance: 2200, ref: 'A'},
    {id: 2, balance: 2100, ref: 'C'}
]
const remote = [
    {id: 1, balance: 3300, ref: 'B'},
]

let result = local.map(e =>{
  let r = remote.find(i => i.id === e.id)
  let ref = r?.ref
  if(ref){
    e.balance = r.balance
    e.ref += ' / ' + ref
   }
  return e
})
console.log(result)

更新:如果你想让你的原始代码有效,你需要添加else块如果没有匹配

const local = [
    {id: 1, balance: 2200, ref: 'A'},
    {id: 2, balance: 2100, ref: 'C'}
]
const remote = [
    {id: 1, balance: 3300, ref: 'B'},
]


function mergeFunc(remoteArray, localArray) {
    const newArray = [];
    //loop over one of the arrays
    for (const localObj of localArray) {
        //for each time, search for object with matching id in other array
        if(remoteArray.some(remoteObj => remoteObj.id === localObj.id)){
            //if found matching id, fetch this other object
            const matchingRemoteObj = remoteArray.find(item => item.id === localObj.id);
            //create new, merged, object
            const newObj = {id:matchingRemoteObj.id, balance: matchingRemoteObj.balance, text:`${localObj.ref} / ${matchingRemoteObj.ref}`}
            //push new value to array
            newArray.push(newObj);
        }else{
          // this will add not match record into result array
          newArray.push(localObj) 
        }
    }
    return newArray;
}

let result = mergeFunc(remote,local)
console.log(result)

【讨论】:

    【解决方案2】:

    您可以使用array.maparray.find方法,

    要用您可以使用的远程数组替换比赛的余额,

    obj.balance = o.balance
    

    要合并匹配 id 的 ref 字符串,您可以使用,

    obj.ref = `${obj.ref} / ${o.ref}`
    

    工作片段:

    const local = [
        { id: 1, balance: 2200, ref: "A" },
        { id: 2, balance: 2100, ref: "C" },
      ];
      const remote = [{ id: 1, balance: 3300, ref: "B" }];
    
      const result = local.map((obj) => {
        remote.find((o) => {
          if (o.id === obj.id) {
            obj.balance = o.balance;
            obj.ref = `${obj.ref} / ${o.ref}`;
          }
        });
        return obj;
      });
    
      console.log(result);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多