符合条件的对象的JavaScript搜索数组
JavaScript search array of objects on condition
我有一个测试对象数组,如下所示,每个测试对象都有一个popupTime
键:
var quizzes = {
"quizzes": [
{
"_id": "546060033ea982a04f2e1859",
"popupTime": 2.24,
"lectureId": 5008,
"__v": 0,
"questions": [
{
"title": "Which is the capital of India",
"_id": "546060033ea982a04f2e185f",
"answerswers": [
{
"answerswer": "Delhi",
"_id": "546060033ea982a04f2e1863",
"correct": true
},
{
"answerswer": "Bangalore",
"_id": "546060033ea982a04f2e1862",
"correct": false
},
{
"answerswer": "Mumbai",
"_id": "546060033ea982a04f2e1861",
"correct": false
},
{
"answerswer": "Chennai",
"_id": "546060033ea982a04f2e1860",
"correct": false
}
]
},
{
"title": "Where is housing located? ",
"_id": "546060033ea982a04f2e185a",
"answerswers": [
{
"answerswer": "Delhi",
"_id": "546060033ea982a04f2e185e",
"correct": false
},
{
"answerswer": "Bangalore",
"_id": "546060033ea982a04f2e185d",
"correct": true
},
{
"answerswer": "Mumbai",
"_id": "546060033ea982a04f2e185c",
"correct": false
},
{
"answerswer": "Chennai",
"_id": "546060033ea982a04f2e185b",
"correct": false
}
]
}
]
},
{
"_id" : "5460640d1e8743ee61413690",
"popupTime" : 169,
"lectureId" : 5008,
"questions" : [
{
"title" : "Is this the 2nd quiz in same lecture?",
"_id" : "5460640d1e8743ee61413691",
"answerswers" : [
{
"answerswer" : "True",
"_id" : "5460640d1e8743ee61413693",
"correct" : true
},
{
"answerswer" : "False",
"_id" : "5460640d1e8743ee61413692",
"correct" : false
}
]
}
],
"__v" : 0
}
]
};
扫描整个测试对象,得到一个满足popupTime = 169
的对象并将其保存在另一个对象中,哪种方法最有效?
在重复调用的执行时间方面效率很高。我将多次对同一个数组执行相同的操作来检查条件。
我建议您使用一个单独的array
,其目的是通过popupTime来index your object
。因此创建一个单独的array
:
var indexArray = [];
每次在quizzes
中插入新的Object
时,也要在此数组中插入popupTime
:
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);
相关文章:
- Javascript:使用用户输入搜索数组
- javascript搜索数组,返回找到的关键字
- 搜索数组并返回值
- 在JavaScript中搜索数组映射的最有效方法
- 使用变量而不是静态字符串搜索数组
- 无法搜索数组项
- 使用下划线搜索数组中的JSON值
- 使用HTML搜索,需要JavaScript来搜索数组并在新窗口中返回结果
- jQuery函数来搜索数组值
- 搜索数组,按查询相关性显示结果
- 在 Javascript 中搜索数组列表的项
- jQuery 搜索数组数组
- 符合条件的对象的JavaScript搜索数组
- 在javascript中搜索数组时忽略大小写
- JavaScript——在对象中搜索数组值
- 使用通配符在JS中搜索数组
- 如何搜索数组数组,并与第一个元素进行比较
- 如何在json文件中搜索数组
- Array.prototype.find搜索数组中的对象
- 使用CategoryFilter搜索数组,而不是匹配列