【问题标题】:lodash comparing objects in an array and create a new object based on this comparisonlodash 比较数组中的对象并基于此比较创建一个新对象
【发布时间】:2020-04-28 00:45:29
【问题描述】:

我有一个对象数组,格式如下:

var res = [
  { StartTime: "04/29/2020 13:30", Status: "free" },
  { StartTime: "04/29/2020 14:00", Status: "free" },
  { StartTime: "04/29/2020 14:30", Status: "free" },
  { StartTime: "04/29/2020 15:00", Status: "free" },
  { StartTime: "04/29/2020 20:00", Status: "free" },
  { StartTime: "04/29/2020 20:30", Status: "free" },
];

现在我想创建一个对象,将这个对象数组拆分为 2 个对象数组,如果 StartTimes 有 30 分钟不同,它们可以保持在一起,否则我将继续创建一个新数组看起来像这样:

var res = [
  [
    { StartTime: "04/29/2020 13:30", Status: "free" },
    { StartTime: "04/29/2020 14:00", Status: "free" },
    { StartTime: "04/29/2020 14:30", Status: "free" },
    { StartTime: "04/29/2020 15:00", Status: "free" },
  ],
  [
    { StartTime: "04/29/2020 20:00", Status: "free" },
    { StartTime: "04/29/2020 20:30", Status: "free" },
  ],
];

我正在使用 moment.js 来查找 2 个日期之间的差异。

【问题讨论】:

    标签: javascript momentjs lodash


    【解决方案1】:

    你可以用普通的 JavaScript 来做,比如:

    var res = [
      { StartTime: "04/29/2020 13:30", Status: "free" },
      { StartTime: "04/29/2020 14:00", Status: "free" },
      { StartTime: "04/29/2020 14:30", Status: "free" },
      { StartTime: "04/29/2020 15:00", Status: "free" },
      { StartTime: "04/29/2020 20:00", Status: "free" },
      { StartTime: "04/29/2020 20:30", Status: "free" },
    ];
    
    let j = 0, result = [], previous;
    for (let i = 0; i < res.length; i++) {
      let current = new Date(res[i].StartTime);
      if (previous && current.getTime() - previous.getTime() > 30 * 60 * 1000) j++;
      (result[j] = result[j] || []).push(res[i]);
      previous = current;
    }
    
    console.log(result);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      • 2018-06-05
      • 2021-10-07
      • 2021-09-19
      相关资源
      最近更新 更多