javascript 在数组中查找对象而不是循环的更好方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15766353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Better way to find object in array instead of looping?
提问by Ron van der Heijden
Example
例子
Link: http://jsfiddle.net/ewBGt/
链接:http: //jsfiddle.net/ewBGt/
var test = [{
"name": "John Doo"
}, {
"name": "Foo Bar"
}]
var find = 'John Doo'
console.log(test.indexOf(find)) // output: -1
console.log(test[find]) // output: undefined
$.each(test, function(index, object) {
if(test[index].name === find)
console.log(test[index]) // problem: this way is slow
})
Problem
问题
In the above example I have an array with objects. I need to find the object that has name = 'John Doo'
在上面的例子中,我有一个包含对象的数组。我需要找到具有name = 'John Doo'
My .each
loop is working, but this part will be executed 100 times and test will contain lot more objects. So I think this way will be slow.
我的.each
循环正在运行,但这部分将被执行 100 次并且测试将包含更多的对象。所以我认为这种方式会很慢。
The indexOf()
won't work because I cannot search for the name in object.
该indexOf()
不会工作,因为我不能搜索的对象名称。
Question
问题
How can I search for the object with name = 'John Doo'
in my current array?
如何name = 'John Doo'
在当前数组中搜索对象?
回答by Matti Simperi
I have done sometimes "searchable map-object" in this kind of situation. If the array itself is static, you can transform in to a map, where array values can be keys and map values indexes. I assume values to be unique as in your example.
在这种情况下,我有时会做“可搜索的地图对象”。如果数组本身是静态的,您可以转换为映射,其中数组值可以是键和映射值索引。我假设值在您的示例中是唯一的。
Lo-Dash (www.lodash.com) has create selection of utils for easily looping etc. Check it out!
Lo-Dash (www.lodash.com) 已经创建了用于轻松循环等的实用程序选择。看看吧!
Note:But often you really don't have to worry about looping trough array with 100 elements.
注意:但通常你真的不必担心循环包含 100 个元素的槽数组。
回答by Luca Fagioli
jQuery $.grep
(or other filtering function) is not the optimal solution.
jQuery $.grep
(或其他过滤功能)不是最佳解决方案。
The $.grep
function will loop through allthe elements of the array, even if the searched object has been already found during the loop.
该$.grep
函数将遍历数组的所有元素,即使在循环过程中已找到搜索对象。
From jQuery grep documentation :
来自 jQuery grep 文档:
The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.
$.grep() 方法根据需要从数组中删除项目,以便所有剩余的项目通过提供的测试。测试是一个函数,它传递一个数组项和数组中该项的索引。只有当测试返回 true 时,该项目才会出现在结果数组中。
Provided that your array is not sorted, nothing can beat this:
如果您的数组未排序,则没有什么比这更好的了:
var getObjectByName = function(name, array) {
// (!) Cache the array length in a variable
for (var i = 0, len = test.length; i < len; i++) {
if (test[i].name === name)
return test[i]; // Return as soon as the object is found
}
return null; // The searched object was not found
}
回答by tomekwi
If you just want to find out if the value is there, you can use lodash's includes
function like this:
如果你只是想知道这个值是否存在,你可以includes
像这样使用 lodash 的函数:
var find = 'John Doo'
[{ "name": "John Doo" }, { "name": "Foo Bar" }].some(function (hash) {
if (_.includes(hash, find)) return true;
});
Documentation:
文档:
回答by sbeliv01
Perhaps you should use the $.grep
functionality in jQuery:
也许您应该使用$.grep
jQuery 中的功能:
var test = [{
"name": "John Doo"
}, {
"name": "Foo Bar"
}]
var find = 'John Doo'
var found = $.grep(test, function(obj){
return obj['name'] == find;
});
console.log(found);
Fiddle: http://jsfiddle.net/ewBGt/3/
回答by CBroe
The only thing you can possibly do is use build-in array methods (if available) in preference over doing the looping yourself – the filter
method would be applicable here.
您唯一能做的就是使用内置数组方法(如果可用)而不是自己进行循环——该filter
方法在这里适用。
But I expect that JS libraries like jQuery used by sbeliv01 in his answer already check for that internally (and provide a fallback solution if these array methods are not available natively) – so don't expect a massive performance boost.
但我希望 sbeliv01 在他的回答中使用的 jQuery 等 JS 库已经在内部检查了它(如果这些数组方法在本机不可用,则提供后备解决方案)——所以不要指望巨大的性能提升。