在javascript中合并部分重复的数组(lodash) [英] merge partially duplicated arrays in javascript (lodash)

查看:124
本文介绍了在javascript中合并部分重复的数组(lodash)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多人在不同的年份买了车. 简化的数组是这样的:

I have a large javascript array of some people Bought a car in different years. the simplified array is like this:

const owners = [{
  name: "john",
  hasCar: true,
  yearBought: 2002
}, {
  name: "john",
  hasCar: true,
  yearBought: 2005
}, {
  name: "mary",
  hasCar: true,
  yearBought: 2015
}, {
  name: "john",
  hasCar: true,
  yearBought: 2018
}]

如果一个人拥有一辆以上的汽车(例如本例中的John),那么在购买汽车的年份不同的人会有不同的对象.我想合并属于每个人的对象,最终结果应该像这样:

if a person has more than one car (like John in this example), there is different objects for him with different years he has bought the car. I want to merge objects belongs to each individual person and the final result should be like this:

const owners = [{
  name: "john",
  hasCar: true,
  yearBought: [2002, 2005, 2018]
}, {
  name: "mary",
  hasCar: true,
  yearBought: 2018
}]

推荐答案

您可以使用 concat 将它们推入数组.否则,在累加器中创建一个新密钥并将其设置为当前对象.然后,使用 Object.values() 将数组的值作为数组获取

You could use reduce the array and group them based on name first. The accumulator is an object with each unique name as key. If the name already exists, use concat to push them into the array. Else, create a new key in the accumulator and set it to the current object. Then, use Object.values() to get the values of the array as an array

const owners = [{name:"john",hasCar:!0,yearBought:2002},{name:"john",hasCar:!0,yearBought:2005},{name:"mary",hasCar:!0,yearBought:2015},{name:"john",hasCar:!0,yearBought:2018}];

const merged = owners.reduce((r, o) => {
  if(r[o.name])
    r[o.name].yearBought = [].concat(r[o.name].yearBought, o.yearBought)
  else
    r[o.name] = { ...o };
  return r;
},{})

console.log(Object.values(merged))

这篇关于在javascript中合并部分重复的数组(lodash)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆