首页 > 解决方案 > 在 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 函数可以做到这一点?

标签: javascriptjqueryarraysjsonperformance

解决方案


您可以使用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; }


推荐阅读