javascript - 在 JavaScript 中简化对象的最佳方法是什么(最好使用 Jquery)
问题描述
我有一个看起来像这样的对象:
var dataSource = [{
date: new Date(1994, 2, 2),
name: "a",
l: 24.00,
h: 25.00,
o: 25.00,
c: 24.875
}, {
date: new Date(1994, 2, 2),
name: "a",
l: 23.625,
h: 25.125,
o: 24.00,
c: 24.875
}, {
date: new Date(1994, 2, 3),
name: "a",
l: 26.25,
h: 28.25,
o: 26.75,
c: 27.00
}, {
date: new Date(1994, 2, 4),
name: "c",
l: 26.50,
h: 27.875,
o: 26.875,
c: 27.25
}, {
依此类推...我想按日期组合条目,这意味着如果两个数据点具有相同的日期和名称,我想将它们加在一起,因此输出将是:
var dataSource = [{
date: new Date(1994, 2, 2),
name: "a",
l: 47.625,
h: 50.125,
o: 49.00,
c: 49.75
}, {
date: new Date(1994, 2, 3),
name: "a",
l: 26.25,
h: 28.25,
o: 26.75,
c: 27.00
}, {
date: new Date(1994, 2, 4),
name: "c",
l: 26.50,
h: 27.875,
o: 26.875,
c: 27.25
}, {
现在我能想到的最好的方法是运行一个 for 循环,直到对象的大小不再改变。有没有更好的方法可以做到这一点,可能是类似于 grep 的 jquery 函数可以做到这一点?
解决方案
您可以使用reduce()
由与名称 ( ) 连接的日期组成的复合键调用分组元素o.date.valueOf() + o.name
,对相关键求和,然后调用Object.values()
结果以返回合并对象的数组。
const dataSource = [{ date: new Date(1994, 2, 2), name: "a", l: 24.00, h: 25.00, o: 25.00, c: 24.875 }, { date: new Date(1994, 2, 2), name: "a", l: 23.625, h: 25.125, o: 24.00, c: 24.875 }, { date: new Date(1994, 2, 3), name: "a", l: 26.25, h: 28.25, o: 26.75, c: 27.00 }, { date: new Date(1994, 2, 4), name: "c", l: 26.50, h: 27.875, o: 26.875, c: 27.25 }];
const
sumKeys = (a, b) => ['l', 'h', 'o', 'c'].forEach(k => a[k] += b[k]),
grouped = Object.values(
dataSource.reduce((a, o) => {
const entry = (a[o.date.valueOf() + o.name] ??= { name: o.name, date: o.date.valueOf(), l: 0, h: 0, o: 0, c: 0 });
sumKeys(entry, o);
return a;
}, {}));
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
或者如果您需要避免逻辑无效分配 (??=)以实现兼容性...
const dataSource = [{ date: new Date(1994, 2, 2), name: "a", l: 24.00, h: 25.00, o: 25.00, c: 24.875 }, { date: new Date(1994, 2, 2), name: "a", l: 23.625, h: 25.125, o: 24.00, c: 24.875 }, { date: new Date(1994, 2, 3), name: "a", l: 26.25, h: 28.25, o: 26.75, c: 27.00 }, { date: new Date(1994, 2, 4), name: "c", l: 26.50, h: 27.875, o: 26.875, c: 27.25 }];
const
sumKeys = (a, b) => ['l', 'h', 'o', 'c'].forEach(k => a[k] += b[k]),
grouped = Object.values(
dataSource.reduce((a, o) => {
const entry = (a[o.date.valueOf() + o.name] = a[o.date.valueOf() + o.name] || { name: o.name, date: o.date.valueOf(), l: 0, h: 0, o: 0, c: 0 });
sumKeys(entry, o);
return a;
}, {}));
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- c++ - 如何在我的ELSE条件下连接IF?
- javascript - 如何将 @ViewChild 与外部 ng 模板一起使用(Angular 11)
- oracle - 如何在 oracle 中将 GMT 转换为 PST 和 PDT 时间
- visual-studio-code - VSCode 错误:终端进程无法启动:shell 可执行文件“/usr/bin/tmux”的路径不存在
- memory-management - 在使用页表的操作系统中,页表是否曾经为空?
- r - 在 Shiny Dashboard 中填充整个 tabItem 窗口
- reactjs - Firestore 是存储许多大型对象的好数据库吗?
- python - Matplotlib:如何使用 FOR 循环制作绘图
- matplotlib - 从 Matplotlib 动画函数更新 Pandas Dataframe
- pandas - 如何将df的部分连接到另一个df