What's the best way to query an array in javascript to get just the items from it I want?

后端 未结 7 1051
悲哀的现实
悲哀的现实 2020-12-13 18:48

I have an array like this (with just over 3000 objects instead of the 3 here):

items = [{name:\'charlie\', age:\'16\'}, {name:\'ben\', age:\'18\'}, {name:\'s         


        
相关标签:
7条回答
  • 2020-12-13 18:58

    making use of javascript magnificent function eval() which evaluates string as code at runtime, we can define a prototype method for Array type

    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');
    
    0 讨论(0)
  • 2020-12-13 19:03

    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.

    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.

    0 讨论(0)
  • 2020-12-13 19:13

    You can use pure 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


    Update

    Speedwise there is a huge varying (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

    0 讨论(0)
  • 2020-12-13 19:15

    Get matched item and items using find() and filter() method

    If you want first matched single item, use find() method which returns single object.

    If you want all matched , use filter() method which returns array of objects.

    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);

    0 讨论(0)
  • 2020-12-13 19:15

    No matter which method you choose (items.filter or any "query language" for json), a for loop is inevitable.

    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.

    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);
        }
    });
    
    0 讨论(0)
  • 2020-12-13 19:16

    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.

    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"]));
    
    0 讨论(0)
提交回复
热议问题