合并数组中的重复对象,并合并每个对象的子数组

阿里·哈利勒(Ali Khalil)

我试图基于Id合并对象,并合并每个account对象(对象)中的每个数组,但是如果存在匹配的ID,则代码将覆盖该数组,而不是合并accountList的内容。

我做了一个新的数组,并使用.find方法根据那里的id查找匹配的对象,但是坚持如何将它们合并accountList在一起

const accounts = [
    {
    "Id": 103,
    "accountList": [
      {}
    ]
  },
  {
    "Id": 103,
    "accountList": [
      {
        "tokenId": "5aasdasdsdnjn3434nadd",
        "featureId": 2840
      }
    ]
  },
  {
    "Id": 112,
    "accountList": [
      {
        "tokenId": "5d30775bef4a722c38aefaaa",
        "featureId": 2877
      }
    ]
  },
    {
    "Id": 112,
    "accountList": [
      {
        "tokenId": "5d30775bef4a722c38aefccc",
        "featureId": 2856
      }
    ]
  }
]

let result = [];
accounts.forEach(account => {
  let match = result.find(r => r.Id === account.Id);
  // console.log(match)
  if(match) {
   Object.assign(match, account);
    //tried using spread operator instead of object assign, but didnt work
    //  match = {...match, ...account}
  } else {
    result.push(account);
  }
});

console.log( JSON.stringify(result, null, 2))

我需要的结果是根据对象的ID合并对象,并将对象的内容合并accountList在一起,如下所示:

[
  {
    "Id": 103,
    "accountList": [
      {
        "tokenId": "5aasdasdsdnjn3434nadd",
        "featureId": 2840
      }
    ]
  },
  {
    "Id": 112,
    "accountList": [
      {
        "tokenId": "5d30775bef4a722c38aefaaa",
        "featureId": 2877
      },
      {
        "tokenId": "5d30775bef4a722c38aefccc",
        "featureId": 2856
      }
    ]
  }
]
叶夫根·戈本科夫(Yevgen Gorbunkov)

我认为reduce()可以胜任:

const accounts = [{"Id":103,"accountList":[{}]},{"Id":103,"accountList":[{"tokenId":"5aasdasdsdnjn3434nadd","featureId":2840}]},{"Id":112,"accountList":[{"tokenId":"5d30775bef4a722c38aefaaa","featureId":2877}]},{"Id":112,"accountList":[{"tokenId":"5d30775bef4a722c38aefccc","featureId":2856}]}];

const result = [...accounts
        .reduce((r, o) => {
          const record = r.get(o.Id)||{}
          r.set(o.Id, {
            Id: o.Id,
            accountList: [
              ...(record.accountList||[]),
              ...o.accountList.filter(o => 
                Object.keys(o).length != 0)
            ]            
          })
          return r
        }, new Map())
        .values()]

console.log(result);
.as-console-wrapper {min-height: 100%}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章