JavaScript搜索条件下的对象数组
我有一个如下的测验对象数组,每个测验对象都有一个JavaScript搜索条件下的对象数组,javascript,Javascript,我有一个如下的测验对象数组,每个测验对象都有一个poputime键: var quizzes = { "quizzes": [ { "_id": "546060033ea982a04f2e1859", "popupTime": 2.24, "lectureId": 5008, "__v": 0, "questions": [
poputime
键:
var quizzes = {
"quizzes": [
{
"_id": "546060033ea982a04f2e1859",
"popupTime": 2.24,
"lectureId": 5008,
"__v": 0,
"questions": [
{
"title": "Which is the capital of India",
"_id": "546060033ea982a04f2e185f",
"answers": [
{
"answer": "Delhi",
"_id": "546060033ea982a04f2e1863",
"correct": true
},
{
"answer": "Bangalore",
"_id": "546060033ea982a04f2e1862",
"correct": false
},
{
"answer": "Mumbai",
"_id": "546060033ea982a04f2e1861",
"correct": false
},
{
"answer": "Chennai",
"_id": "546060033ea982a04f2e1860",
"correct": false
}
]
},
{
"title": "Where is housing located? ",
"_id": "546060033ea982a04f2e185a",
"answers": [
{
"answer": "Delhi",
"_id": "546060033ea982a04f2e185e",
"correct": false
},
{
"answer": "Bangalore",
"_id": "546060033ea982a04f2e185d",
"correct": true
},
{
"answer": "Mumbai",
"_id": "546060033ea982a04f2e185c",
"correct": false
},
{
"answer": "Chennai",
"_id": "546060033ea982a04f2e185b",
"correct": false
}
]
}
]
},
{
"_id" : "5460640d1e8743ee61413690",
"popupTime" : 169,
"lectureId" : 5008,
"questions" : [
{
"title" : "Is this the 2nd quiz in same lecture?",
"_id" : "5460640d1e8743ee61413691",
"answers" : [
{
"answer" : "True",
"_id" : "5460640d1e8743ee61413693",
"correct" : true
},
{
"answer" : "False",
"_id" : "5460640d1e8743ee61413692",
"correct" : false
}
]
}
],
"__v" : 0
}
]
};
扫描整个测验对象并获取一个满足popupTime=169
的对象并将其保存到另一个对象中的最有效方法是什么
在重复调用的执行时间方面效率很高。我将在同一数组上多次执行相同的操作以检查条件。我建议您使用一个单独的
数组
,其目的是通过popupTime对对象进行索引。因此,创建一个单独的数组
:
var indexArray = [];
每次将新的对象
插入测验
时,也要将弹出时间
插入此数组:
indexArray.push(yournewObject.popupTime);
然后,您可以使用Array.prototype.indexOf
方法找到您的元素:
var yourSearchedObject = quizzes[indexArray.indexOf(169)];
您可以通过
popupTime
为集合编制索引,以执行O(1)
查找。假设popupTime
是唯一的
function index(collection, by) {
var cache = {}, i = 0, len = collection.length, item;
for(; i < len; ++i) { //for is faster than forEach and it's friends
item = collection[i];
cache[item.key] = item;
}
return function findOne(key) {
return cache[key];
}
}
var findByPopupTime = index(quizzes.quizzes, 'popupTime');
var quiz169 = findByPopupTime(169);
函数索引(集合,按){
var cache={},i=0,len=collection.length,item;
for(;i
Array.prototype.filter
定义“效率”。执行时间?重复调用的执行时间?更少的代码行?重复调用的执行时间。我将在同一阵列上多次执行相同的操作,以检查是否存在您不担心效率的情况。或者更确切地说,您首先需要担心时间的效率,包括最初的编码和维护。第一步是写一些有用的东西。然后,你可以担心使它高效,事实上它确实是你的代码中的一个瓶颈,这是极不可能的。@ Trasababuro你的权利,但我想考虑所有的选项和最好的方式,其他开发人员会这样做。只是探索最好的方式这可能是不可能的,因为我正在从mongoDb服务中调出这些测验。它给了我一个对象的大数组,你可以在这个大数组上迭代一次,然后设置你的索引数组,这很有用