我有以下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;
}
问题是它不断返回项目i。我认为函数find会遍历所有条目。
我无法找到不同的解决方案。
我需要保持时间的顺序。
任何指针......?
答案 0 :(得分:1)
不确定您到底在尝试什么。使用type mismatch
的理想方法是_.find
匹配(并且不会迭代下一个元素)。
从谓词return true
开始,return true
会返回该键的值。
当你从谓词中_.find
获得匹配元素时:
return true
会返回第一场比赛的值
_.find
会返回上一场比赛的值
_.findLast
会返回第一场比赛的键
_.findKey
会返回上一场比赛的键
_.findLastKey
会将所有匹配项的值作为数组返回
注意:如果您想获得最近的即将到来的时间,您需要在传递给任何这些lodash函数之前对_.filter
进行排序。
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));

答案 1 :(得分:0)
您可以使用Object.entries()
将JSON
作为javascript
对象进行迭代,使用+
运算符和.replace()
将日期转换为整数。如果condition为true
,则将对象的属性设置为current属性和value。
const data = {
"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"
}
}
let res = {};
// let now = `${new Date().toJSON()}`.slice(11, 16);
let now = "21:26";
let dateToNumber = str => +str.replace(/:/, "");
for (let [key, prop] of Object.entries(data.timings)) {
if (dateToNumber(prop) >= dateToNumber(now)) {
// do stuff
res[key] = prop;
}
}
console.log(res);

答案 2 :(得分:0)
您可以使用lodash#findKey
从对象中查找特定密钥。
const findTime = times => {
let mNow = moment();
let name = _.findKey(times, v => moment(v, 'HH:mm').isSameOrAfter(mNow));
var time = times[name];
return time? { name, time }: null;
};
let data = {
"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"
}
};
const findTime = times => {
let mNow = moment();
let name = _.findKey(times, v => moment(v, 'HH:mm').isSameOrAfter(mNow));
var time = times[name];
return time? { name, time }: null;
};
console.log(findTime(data.timings));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;