简体   繁体   中英

Javascript [jQuery] filter array by key and value

I need to filter an array if a key meets a certain value, for example:

data = theArray;
var theColumn = "thc012";
var theVal = 4;
data = $.filter(data, theColumn, theVal );

And then the result would be all the array items that match theColumn = theVal ;

I am already using the jQuery Library so if any jQuery functions help, use them.

Thanks

Javascript objects are key-value pairs. You can use them. Like so:

var data = {
    "cars": ["Honda", "Toyota", "Subaru"],
    "planes": ["Boeing", "Airbus", "Mig"]
};
var key = "cars";
data[key]; // All cars
key = "planes";
data[key]; // All planes

I think you're looking for the grep method: jQuery.grep

Then just supply it with a function that checks if theColumn = theKey;

if i have understood your question correctly this should do it

 $.each(data,function(row,key){ 
    if(key != theKey && theColumn != theColumn){
        delete data[key];
    } 
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM