在 javascript 中查询数组以从中获取我想要的项目的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5257786/
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
What's the best way to query an array in javascript to get just the items from it I want?
提问by Kenny Flannery
I have an array like this (with just over 3000 objects instead of the 3 here):
我有一个这样的数组(只有 3000 多个对象,而不是这里的 3 个):
items = [{name:'charlie', age:'16'}, {name:'ben', age:'18'}, {name:'steve', age:'18'}]
What's the best way to return an array with just the objects of people who are 18? So I want:
返回仅包含 18 岁人群对象的数组的最佳方法是什么?所以我想要:
items = [{name:'ben', age:'18'}, {name:'steve', age:'18'}]
The best I can think of is this (using jQuery):
我能想到的最好的就是这个(使用 jQuery):
newArray = []
$.each(items, function(index, item) {
if(item.age=='18') {
newArray.push(item)
}
})
Considering that there's 3000 thousand objects, and also that I'll be doing that comparison up to fifty times in one go, that's a lot of looping. Is there a better way?
考虑到有 300 万个对象,而且我将一次最多进行 50 次这样的比较,这是很多循环。有没有更好的办法?
回答by Gabriele Petrioli
You can use pure javascript
您可以使用纯 javascript
var wanted = items.filter( function(item){return (item.age==18);} );
And if your browser does not support the 1.6 version of javascript you can find an implementation of the filter method at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
如果您的浏览器不支持 1.6 版本的 javascript,您可以在https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter找到 filter 方法的实现
Update
更新
Speedwise there is a hugevarying (had an error in the test)difference from a normal loop (depending on browser).. Have a look at this little test i made at http://jsperf.com/array-filter-vs-loop/3
Speedwise有一个巨大的变(曾在测试中的错误),从正常的循环差(取决于浏览器)..看一看这个小测试,我在做http://jsperf.com/array-filter-vs-循环/3
回答by david
If you're going to do the search often it may be best to keep a version of your data in a form that is quick to access. I've used underscore.js (http://documentcloud.github.com/underscore/) to make it easy for myself, but this code here will create an object that holds your data indexed by the age field.
如果您要经常进行搜索,最好将您的数据版本保存在可快速访问的形式中。我已经使用 underscore.js (http://documentcloud.github.com/underscore/) 来简化自己的操作,但是这里的代码将创建一个对象,其中包含按年龄字段索引的数据。
You end up with something that looks like this:
您最终会得到如下所示的内容:
{
"16": [
{
"name": "charlie",
"age": "16"
}
],
"18": [
{
"name": "ben",
"age": "18"
},
{
"name": "steve",
"age": "18"
}
]
}
The code:
编码:
var itemsByAge = _(items).reduce(function(memo, item) {
memo[item.age] = memo[item.age] || [];
memo[item.age].push(item);
return memo;
}, {});
alert(JSON.stringify(itemsByAge["18"]));
回答by Sumit
No matter which method you choose (items.filter or any "query language" for json), a for loop is inevitable.
无论您选择哪种方法(items.filter 或 json 的任何“查询语言”),for 循环都是不可避免的。
If performance is a concern, I would recommend you to use pure javascript instead of libraries like jQuery which will add overheads to the whole processing as is evident here.
如果性能是一个问题,我会建议您使用纯 javascript 而不是像 jQuery 这样的库,这会增加整个处理的开销,正如这里显而易见的。
Thus, your code would look like:
因此,您的代码如下所示:
var newArray = [];
for(var i=0;i<items.length;i++) {
var item = items[i];
if(item.age == '18') {
newArray.push(item);
}
});
回答by Mohamed Selim
making use of javascript magnificent function eval()
which evaluates string as code at runtime, we can define a prototype method for Array type
利用 javascript 华丽的函数eval()
在运行时将字符串作为代码进行评估,我们可以为 Array 类型定义一个原型方法
Array.prototype.where = function (query) {
var newArray = [];
for(var i=0; i<this.length; i++) {
var item = this[i];
if(eval( "item" + query )) {
newArray.push(item);
}
}
return newArray;
};
and use it with any array, passing the query as string
并将其与任何数组一起使用,将查询作为字符串传递
var newArray= items.where('.age >= 18');
回答by Vahid Akhtar
Get matched item and items using find() and filter() method
使用 find() 和 filter() 方法获取匹配的项目和项目
If you want first matched single item, use find()method which returns single object.
如果您想要第一个匹配的单个项目,请使用返回单个对象的find()方法。
If you want all matched, use filter()method which returns array of objects.
如果你想要所有匹配的,使用filter()方法返回对象数组。
let items = [{name:'charlie', age:'16'},
{name:'ben', age:'18'},
{name:'steve', age:'18'}]
let all = items.filter(item=> item.age==='18')
console.log(all);
let single = items.find(item=> item.age==='18')
console.log(single);
回答by Mamoon ur Rasheed
once i had such problem and i solved it like this 1- create an array of array 2- each index create an Index record e.g.
一旦我遇到这样的问题并且我像这样解决了它 1-创建一个数组数组 2-每个索引创建一个索引记录,例如
var pAry=[];
var cAry=[{name:'ben', age:'18'}, {name:'steve', age:'18'}]
pAry[17]=cAry;
This way when u require person with age 18, you will get on index 17.
这样,当您需要 18 岁的人时,您将获得索引 17。
回答by CloudyMarble
Use the filter method of the array, it calls the provided callbackfunction once for each element in an array.
使用数组的 filter 方法,它为数组中的每个元素调用一次提供的回调函数。
array.filter(<callbackfucntion>[, <Object to use>])