如何按日期从对象中删除数据

时间:2019-07-03 09:23:47

标签: javascript react-native

如何从13小时前添加的对象中删除具有其值的属性

如果对象中的数据存在时间超过 12 小时,我想将其删除。

示例:

const myData = {
   user1: {date: '', data: [...]},  // added to myData 1 hour ago
   user2: {date: '', data: [...]},  // added to myData 5 hour ago
   user3: {date: '', data: [...]},  // added to myData 12 hour ago
   user4: {date: '', data: [...]},  // added to myData 13 hour ago
   user5: {date: '', data: [...]},  // added to myData 15 hour ago
}

在这里,我要删除 user4 user5 ,因为它们是在12个小时前添加的。

2 个答案:

答案 0 :(得分:2)

您可以每小时运行一次Object.entries()迭代并检查旧数据(每次执行都根据需要设置maxDate

var obj = {
  user1: {
    date: new Date(2019,6,3,12,0,0)
  },
  user2: {
    date: new Date(2019,6,3,13,0,0)
  }
}

console.log(obj);

var maxDate = new Date(2019,6,3,12,30,0); 
Object.entries(obj).forEach(x => {  
  const date = x[1].date;
  if (date > maxDate) {
    delete obj[x[0]]
  }
})

console.log(obj);


编辑

使用间隔检查此示例

const checkEntries = function() {
    var maxDate = getMaxDate();
    Object.entries(obj).forEach(x => {  
      const date = x[1].date;
      if (date > maxDate) {
        delete obj[x[0]]
      }
    });
}

/*
 * Get the time, 12 hours ago
 */ 
function getMaxDate() {
    const now = new Date();
    const now_tm = now.getTime();
    const maxDate_tm = now_tm - (12*60*60*1000);
    return new Date(maxDate_tm);
}

const timer = setInterval(checkEntries, 3600000);

答案 1 :(得分:2)

您可以使用以下表达式获取两个日期之间的小时数:

(addedDate - now) / 3.6e6

(其中addedDatenowDate对象)。如果结果表达式小于或等于-12,则addedDate比确切时间早12个小时。

addedDate - now返回两个日期之间的毫秒差。除以3,600,000,将以小时为单位返回该值。

您可以使用它定期过滤您的条目:

const now = new Date();

const updatedData = Object.entries(myData).reduce((accumulator, [key, value]) => {
    // if time difference is higher than -12, keep the record
    if ((value.addedDate - now) / 3.6e6 > -12) {
        return {...accumulator, [key]: value};
    }
    // otherwise, skip the record, and just return the accumulator
    return accumulator;
}, {});

如果您的日期属性不是Date对象,请先将其转换为该对象。

相关问题