下午好,我遇到了困难。我遇到了一个无法解决的问题。我有一个对象数组:
[
{
date: "2020-04-20",
groups: ["apple"],
type: ["fruit"],
},
{
date: "2020-04-20",
groups: ["potate"],
type: ["vegetable"],
},
{
date: "2020-04-23",
groups: ["burger"],
type: ["fastfood"],
},
{
date: "2020-04-24",
groups: ["cola"],
type: ["water"],
}
]
我需要编写一个函数来确定按日期将两个对象合二为一。 也就是说,函数返回的预期结果应该是这样的:
[
{
date: "2020-04-20",
groups: ["apple", "potate"],
type: ["fruit", "vegetable"],
},
{
date: "2020-04-23",
groups: ["burger"],
type: ["fastfood"],
},
{
date: "2020-04-24",
groups: ["cola"],
type: ["water"],
}
]
预先感谢您的帮助!
最佳答案
首先,考虑一下您想要实现的目标。您想要将数据合并在一起。 Array.prototype.reduce 是实现此目的以及从一种数据结构更改为另一种数据结构的好工具。
从概念上讲,我建议在日期和整个对象之间创建一个映射。这将帮助您确定该条目是否已存在。然后,您可以在迭代时将相关键推送到相关数组。最后,您可以使用Object.values
仅获取您创建的 map 的值。
这是我在处理此类情况时经常使用的模式。
我会做如下的事情:
const input = [
{
date: "2020-04-20",
groups: ["apple"],
type: ["fruit"],
},
{
date: "2020-04-20",
groups: ["potate"],
type: ["vegetable"],
},
{
date: "2020-04-23",
groups: ["burger"],
type: ["fastfood"],
},
{
date: "2020-04-24",
groups: ["cola"],
type: ["water"],
}
];
const combine = (arr) => {
const dateMap = arr.reduce((acc, item) => {
if (!acc[item.date]) {
acc[item.date] = item;
} else {
acc[item.date].groups = [...acc[item.date].groups, ...item.groups];
acc[item.date].type = [...acc[item.date].type, ...item.type];
}
return acc;
}, {});
return Object.values(dateMap);
};
console.log(combine(input));
关于javascript - 如何编写一个函数,通过数组从多个对象创建一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61417434/