"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
。
答案 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