我是Linq.js新手,正在尝试获取json字符串的一个子集。我的Json字符串如下: eventJSON:
[{"EventID": "1", "Description": "Hello World", "EventTime": "16123456000"},
{"EventID": "2", "Description": "Carpe Diem", "EventTime": "16123656000"},
{"EventID": "3", "Description": "Desc3", "EventTime": "16123656000"}] 我有一个遍历这个json的函数,并尝试根据eventtime值返回一个子集。THe代码如下:
videoPlayer.on('playtime', function (pts) {
var pts = 16123656000;
if (eventJSON != null) {
var _resultArray = Enumerable.From(eventJSON).Select(function (eventrecord) { return Number(eventrecord.EventTime) == Number(pts); }).ToArray();
if (_resultArray.length > 0) {
_resultArray.forEach(function (item, index, array) {
console.log(item.EventTime);
}
)
}
}
});这似乎不起作用。如何将json的子集作为数组获取并遍历它们?
发布于 2021-06-25 02:36:43
你不需要linq.js来做这件事。只需使用Array.filter即可
let data = [{"EventID": "1", "Description": "Hello World", "EventTime": "16123456000"},
{"EventID": "2", "Description": "Carpe Diem", "EventTime": "16123656000"},
{"EventID": "3", "Description": "Desc3", "EventTime": "16123656000"}];
let pts = 16123656000;
let filtered = data
.filter(x => +x.EventTime === pts);
filtered.forEach(x => console.log(x.EventTime));对于第二个需求,您可以使用Array.sort、Array.find或Array.reduce
//find latest with <= pts Variant 1
//sort descending and find the first element that meets the condition
let latest = data
.sort((a,b) => +b.EventTime - +a.EventTime)
.find(x => +x.EventTime <= pts)
//Variant 2
//filter all elements meeting the condition, sort descending
//and take the first element
let latest = data
.filter(x => +x.EventTime <= pts)
.sort((a,b) => +b.EventTime - +a.EventTime)[0]
//Variant 3
//using reduce and search for the maximum meeting the condition
let latest = data.reduce((a, c) => {
if (+c.EventTime > pts) return a;
if (!a) return c;
return +a.EventTime > +c.EventTime ? a : c;
}, undefined);https://stackoverflow.com/questions/68121033
复制相似问题