当前位置: 首页 > 知识库问答 >
问题:

在Javascript中基于公共值合并同一数组中的对象[重复]

郑景胜
2023-03-14

我有一个数组:

[
  {
    assignmentId:17,
    email:"john.smith@email.com"
    expectation: "Make sure to proofread!",
    firstName:"John"
    id:23
    ignoreForFeedback: true
    lastName:"Smith"
    level:2
    levelFraction:null
    score:35
  },
  {
    assignmentId:17
    countsPerCategory: Array(4)
    email:"john.smith@email.com"
    firstName:"John"
    frequentErrors: Array(5)
    id:23
    ignoreForGrading: true
    lastName:"Smith"
  },
  {
    assignmentId:17,
    email:"cl@email.com"
    expectation: "cite sources",
    firstName:"Cindy"
    id:45
    ignoreForFeedback: true
    lastName:"Lee"
    level:2
    levelFraction:null
    score:32
  },
  {
    assignmentId:17
    countsPerCategory: Array(4)
    email:"cl@email.com"
    firstName:"Cindy"
    frequentErrors: Array(5)
    id:45
    ignoreForGrading: true
    lastName:"Lee"
  }
]

我想将具有相同“ID”的对象组合成数组中的相同对象。它们的共同密钥也应该组合在一起(例如:'名字'、'电子邮件')。有人能建议做这件事的最好方法吗?使用ES6或Lodash

共有1个答案

丌官博文
2023-03-14

您可以使用LODASH#GROUPBYID对数组中的所有项进行分组,然后使用LODASH#MAP的迭代对象LODASH#Assign,该迭代对象用LODASH#Spread包装,使数组作为LODASH#AssGIN的参数列表进行回调。

var result = _(array)
  .groupBy('id')
  .map(_.spread(_.assign))
  .value();
var array = [
  {
    assignmentId:17,
    email:"john.smith@email.com",
    expectation: "Make sure to proofread!",
    firstName:"John",
    id:23,
    ignoreForFeedback: true,
    lastName:"Smith",
    level:2,
    levelFraction:null,
    score:35
  },
  {
    assignmentId:17,
    countsPerCategory: Array(4),
    email:"john.smith@email.com",
    firstName:"John",
    frequentErrors: Array(5),
    id:23,
    ignoreForGrading: true,
    lastName:"Smith"
  },
  {
    assignmentId:17,
    email:"cl@email.com",
    expectation: "cite sources",
    firstName:"Cindy",
    id:45,
    ignoreForFeedback: true,
    lastName:"Lee",
    level:2,
    levelFraction:null,
    score:32
  },
  {
    assignmentId:17,
    countsPerCategory: Array(4),
    email:"cl@email.com",
    firstName:"Cindy",
    frequentErrors: Array(5),
    id:45,
    ignoreForGrading: true,
    lastName:"Lee"
  }
];

var result = _(array)
  .groupBy('id')
  .map(_.spread(_.assign))
  .value();
  
console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
 类似资料: