【发布时间】:2021-09-02 16:24:49
【问题描述】:
我有两个对象数组,如下所示:
array1 = [
{ material: "ABC123", cost: 100 },
{ material: "DEF456", cost: 150 }
]
array2 = [
{ material: "ABC123", date: "1/1/20", quantity: 4 },
{ material: "ABC123", date: "1/15/20", quantity: 1 },
{ material: "ABC123", date: "2/15/20", quantity: 3 },
{ material: "ABC123", date: "4/15/21", quantity: 1 },
{ material: "DEF456", date: "3/05/20", quantity: 6 },
{ material: "DEF456", date: "3/18/20", quantity: 1 },
{ material: "DEF456", date: "5/15/21", quantity: 2 }
]
我想创建一个新的对象数组,其中包括 array1 中的所有键/值对以及每个项目按年份和月份的聚合数量。
结果是:
[
ABC123: {
cost: 100,
byYear: {
2020: {
byMonth: {
1: 5,
2: 3
}
}
},
{
2021: {
byMonth: {
4: 1
}
}
},
},
DEF456: {
cost: 150,
byYear: {
2020: {
byMonth: {
3: 7,
2: 3
}
}
},
{
2021: {
byMonth: {
5: 2
}
}
},
}
]
到目前为止,以下是我的代码,使用的是 lodash,但解决方案中不需要。我遇到的问题是在每个项目下创建的年和月键并不特定于该项目。每个项目都获取所有项目都存在的年份和月份键。
let itemSummary = {};
_.forEach(array1, function (item) {
itemSummary[item["material"]] = itemSummary[item["material"]] || {}; // create material as key
itemSummary[item["material"]] = item; // add props from array1 under each key
_.forEach(array2, function (trans) {
// iterate through transactions and aggregate by year and month
let transactionYear = new Date(trans["date"]).getFullYear();
let transactionMonth = new Date(trans["date"]).getMonth() + 1;
itemSummary[item["material"]]["byYear"] = itemSummary[item["material"]]["byYear"] || {}; //create year key
itemSummary[item["material"]]["byYear"][transactionYear] = itemSummary[item["material"]]["byYear"][transactionYear] || {}; // set year key
itemSummary[item["material"]]["byYear"][transactionYear]["byMonth"] = itemSummary[item["material"]]["byYear"][transactionYear]["byMonth"] || {};
itemSummary[item["material"]]["byYear"][transactionYear]["byMonth"][transactionMonth] =
itemSummary[item["material"]]["byYear"][transactionYear]["byMonth"][transactionMonth] || {};
});
});
显然,这并没有像我上面提到的那样汇总数量,因为我首先需要为每个项目获取正确的年份和月份键。
非常感谢任何帮助
【问题讨论】:
-
为什么是
material/part或part/item?为什么结果是数组? -
不错,错字。一切都应该是物质的,更新了帖子。也可以取一个对象作为结果。
标签: javascript arrays object lodash