【发布时间】:2019-05-01 06:35:11
【问题描述】:
我有很多人在不同年份买了一辆车。 简化后的数组是这样的:
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
}]
如果一个人拥有不止一辆汽车(如本例中的约翰),那么对于他购买汽车的不同年份会有不同的对象。我想合并属于每个人的对象,最终结果应该是这样的:
const owners = [{
name: "john",
hasCar: true,
yearBought: [2002, 2005, 2018]
}, {
name: "mary",
hasCar: true,
yearBought: 2018
}]
【问题讨论】:
-
我认为您不需要 Lodash。只需检查具有给定名称的元素是否存在,如果存在,将年份推送到
yearsBought,如果不存在,只需将新元素推送到列表中
标签: javascript arrays lodash