我有以下 json 格式
{
"timings": {
"a": "02:57",
"b": "05:19",
"c": "13:22",
"d": "17:39",
"e": "21:26",
"f": "21:26",
"g": "23:40",
"h": "02:47",
"i": "01:22"
}
}
使用lodash和momentjs,我如何选择值与当前时间相同或在当前时间之后的对象。
我尝试过以下方法
let findTime = (times) => {
const timeNow = moment();
let nextEvent = null;
lodash.find(times, function (value, key) {
const thisTime = moment(value, 'HH:mm');
if (thisTime.isSameOrAfter(timeNow, 'second')) {
console.log(key + " is next");
nextEvent = {
'name': key,
'time': value
};
return;
}
});
return nextEvent;
}
问题是它无论如何都会返回该项目。我认为函数 find 会迭代所有条目。
我无法找到不同的解决方案。
我需要维护时代的秩序。
有什么指示吗...?
最佳答案
不确定您到底在尝试什么。使用 _.find 的理想方法是为匹配返回 true(并且不会迭代下一个元素)。
当您从谓词中返回 true
时,_.find
将返回该键的值。
当您从匹配元素的谓词中返回 true
时:
_.find
返回第一个匹配的值
_.findLast
返回上一次匹配的值
_.findKey
返回第一个匹配的key
_.findLastKey
返回上一场比赛的key
_.filter
以数组形式返回所有匹配项的值
注意:如果您想获取最近的即将到来的时间,则需要在传递给任何这些 lodash 函数之前对 timings
进行排序。
let findTime = (times) => {
const timeNow = moment();
let nextEvent = null;
let ret = _.find(times, function (value, key) {
const thisTime = moment(value, 'HH:mm');
if (thisTime.isSameOrAfter(timeNow, 'second')) {
console.log(key + " is next");
nextEvent = {
'name': key,
'time': value
};
return true;
}
});
//return nextEvent;
return ret; // send the return value from lodash function
}
let times = {
"timings": {
"a": "02:57",
"b": "05:19",
"c": "13:22",
"d": "17:39",
"e": "21:26",
"f": "21:26",
"g": "23:40",
"h": "02:47",
"i": "01:22"
}
}
console.log('returned value:', findTime(times.timings));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
关于javascript - 使用 Lodash 根据值从 json 获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44059909/