如何在javascript中通过ID合并多个对象数组?

我想将4个对象数组合并为一个数组

例如:4个数组

var arr1 =[
  { memberID : "81fs", RatingCW:4.5},
  { memberID : "80fs", RatingCW:4},
  { memberID : "82fs", RatingCW:5 },
  { memberID : "83fs", RatingCW:3},
  { memberID : "84fs", RatingCW:4.7}
];
var arr2 =[
  { memberID : "80fs", ratingWW: 4},
  { memberID : "81fs", ratingWW: 4.5},
  { memberID : "83fs", ratingWW: 3},
  { memberID : "82fs", ratingWW: 5},
  { memberID : "84fs", ratingWW: 3.5}
];

var arr3 =  [
  { memberID : "80fs", incoCW:4},
  { memberID : "81fs", incoCW:4.5},
  { memberID : "82fs", incoCW:5},
  { memberID : "83fs", incoCW:3},
  { memberID : "84fs", incoCW:4.5}
  ];
var arr4 =  [
  { memberID : "80fs", incoWW:3},
  { memberID : "81fs", incoWW:2.5 },
  { memberID : "82fs", incoWW:5 },
  { memberID : "83fs", incoWW:3 },
  { memberID : "84fs", incoWW:6.5 }
];

和期望的数组如:

var finalArr = [
    { memberID : "80fs", RatingCW:4,ratingWW: 4, incoCW:4, incoWW:3},
    { memberID : "81fs", RatingCW:4.5,ratingWW: 4.5, incoCW:4.5, incoWW:2.5 },
    { memberID : "82fs", RatingCW:5,ratingWW: 5, incoCW:5, incoWW:5 },
    { memberID : "83fs", RatingCW:3,ratingWW: 3, incoCW:3, incoWW:3 },
    { memberID : "84fs", RatingCW:4.7,ratingWW: 3.5, incoCW:4.5, incoWW:6.5 }
  ];

使用lodash或普通javascript进行合并的最佳方法是什么?

解决方法:

使用lodash,我认为更具可读性.

var arr1 = [{"memberID":"81fs","RatingCW":4.5},{"memberID":"80fs","RatingCW":4},{"memberID":"82fs","RatingCW":5},{"memberID":"83fs","RatingCW":3},{"memberID":"84fs","RatingCW":4.7}],
    arr2 = [{"memberID":"80fs","ratingWW":4},{"memberID":"81fs","ratingWW":4.5},{"memberID":"83fs","ratingWW":3},{"memberID":"82fs","ratingWW":5},{"memberID":"84fs","ratingWW":3.5}],
    arr3 = [{"memberID":"80fs","incoCW":4},{"memberID":"81fs","incoCW":4.5},{"memberID":"82fs","incoCW":5},{"memberID":"83fs","incoCW":3},{"memberID":"84fs","incoCW":4.5}],
    arr4 = [{"memberID":"80fs","incoWW":3},{"memberID":"81fs","incoWW":2.5},{"memberID":"82fs","incoWW":5},{"memberID":"83fs","incoWW":3},{"memberID":"84fs","incoWW":6.5}];

var merged = _(arr1)
  .concat(arr2, arr3, arr4)
  .groupBy("memberID")
  .map(_.spread(_.merge))
  .value();

console.log(merged);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>

这是codepen:http://codepen.io/kuhnroyal/pen/Wxzdmw

上一篇:javascript – Lodash从重复的对象键创建集合


下一篇:javascript – 如何将包含对象的对象转换为对象数组