LowDB获取具有最高时间戳的对象

时间:2018-10-26 11:44:25

标签: javascript node.js ecmascript-6

      "log": [
        {
          "id": "H1AXR_ns7",
          "batt": 80,
          "lat": "lat here",
          "lon": "lon here",
          "tst": 1540552932
        },
       {
          "id": "H1AXR_ns7",
          "batt": 80,
          "lat": "lat here",
          "lon": "lon here",
          "tst": 1540531234
        },
       {
          "id": "H1AXR_ns7",
          "batt": 80,
          "lat": "lat here",
          "lon": "lon here",
          "tst": 1540511234
       }
  ]

在LowDB中,我想为ID为tst的用户过滤并获取具有最高H1AXR_ns7值的对象。

我不确定该怎么做:

到目前为止,我有以下代码:

  db.get('log')
        .find(id)
        .filter().value()

我知道我必须在.filter()中编写一个表达式,但是我不知道如何为ID为tst的用户编写表达式来获得最高的H1AXR_ns7

2 个答案:

答案 0 :(得分:1)

let [highest] = log.sort((a,b)=>a.tst - b.tst)

// highest holds that object now

答案 1 :(得分:1)

const id = 'H1AXR_ns7';
const getMax = (accumulator, currentValue) => accumulator.tst < currentValue.tst? currentValue: accumulator;
const latest = log
  .filter(p => p.id === id)
  .reduce(getMax);

过滤器的文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

reduce的文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce