如何根据现有键值减少数组中的对象
How to reduce objects in an array based off an existing key value
所以我有一个包含三个对象的现有数组:
[ { date: 3/12/2022, oService: 10}
{ date: 3/13/2022, oService: 12, aService: 1}
{ date: 3/13/2022, oService: 1 }]
根据日期,我想得到如下所示的内容:
[ {date: 3/12/2022, oService: 10}
{date: 3/13/2022, oService: 13, aService: 1}]
此外,我最多可以有 10 个服务,所以我无法减少 prev.oService。我将拥有一系列类似于以下内容的服务:
const Services = [aService, bService, cService, oService, yService]
我认为最好将问题视为 2 个不同的步骤:
- 首先,将属于同一日期的所有事物放在一起。这是一个
groupBy
您应该能够在 Whosebug 上查找或从现有库中借用的。
- 然后,您将每个日期组合并到一个对象中。
merge
操作比 groupBy
操作更加自定义。您可以通过多种方式实现它。我建议:
- 实施
merge
以仅处理 2
个对象
- 在
merge
内,遍历这些对象中的所有唯一键并对它们求和(不包括 date
键)
- 要将
merge
应用于日期组,请使用 reduce
。请注意,这里不提供种子参数是安全的,因为保证不会有空组。
// Merge two date-service entries in to one
const merge = (a, b) => {
const merged = Object.assign({}, a);
Object.keys(b).forEach(k => {
if (k !== "date")
merged[k] = (merged[k] || 0) + b[k];
});
return merged;
};
const input = [ { date: "3/12/2022", oService: 10},
{ date: "3/13/2022", oService: 12, aService: 1},
{ date: "3/13/2022", oService: 1 }];
// Create groups that have a matching date
const byDate = groupByProp("date", input);
// Reduce each group to a single item by merging
const all = Object.values(byDate).map(xs => xs.reduce(merge));
console.log(all);
// A basic `groupBy` implementation
function groupByProp(prop, xs) {
return xs.reduce(
(groups, x) => {
const k = x[prop];
if (!groups[k]) groups[k] = [x];
else groups[k].push(x);
return groups;
},
{}
);
}
所以我有一个包含三个对象的现有数组:
[ { date: 3/12/2022, oService: 10}
{ date: 3/13/2022, oService: 12, aService: 1}
{ date: 3/13/2022, oService: 1 }]
根据日期,我想得到如下所示的内容:
[ {date: 3/12/2022, oService: 10}
{date: 3/13/2022, oService: 13, aService: 1}]
此外,我最多可以有 10 个服务,所以我无法减少 prev.oService。我将拥有一系列类似于以下内容的服务:
const Services = [aService, bService, cService, oService, yService]
我认为最好将问题视为 2 个不同的步骤:
- 首先,将属于同一日期的所有事物放在一起。这是一个
groupBy
您应该能够在 Whosebug 上查找或从现有库中借用的。 - 然后,您将每个日期组合并到一个对象中。
merge
操作比 groupBy
操作更加自定义。您可以通过多种方式实现它。我建议:
- 实施
merge
以仅处理2
个对象 - 在
merge
内,遍历这些对象中的所有唯一键并对它们求和(不包括date
键) - 要将
merge
应用于日期组,请使用reduce
。请注意,这里不提供种子参数是安全的,因为保证不会有空组。
// Merge two date-service entries in to one
const merge = (a, b) => {
const merged = Object.assign({}, a);
Object.keys(b).forEach(k => {
if (k !== "date")
merged[k] = (merged[k] || 0) + b[k];
});
return merged;
};
const input = [ { date: "3/12/2022", oService: 10},
{ date: "3/13/2022", oService: 12, aService: 1},
{ date: "3/13/2022", oService: 1 }];
// Create groups that have a matching date
const byDate = groupByProp("date", input);
// Reduce each group to a single item by merging
const all = Object.values(byDate).map(xs => xs.reduce(merge));
console.log(all);
// A basic `groupBy` implementation
function groupByProp(prop, xs) {
return xs.reduce(
(groups, x) => {
const k = x[prop];
if (!groups[k]) groups[k] = [x];
else groups[k].push(x);
return groups;
},
{}
);
}