JavaScript: How to create an Object and filter on those attributes? [duplicate] JavaScript: How to create an Object and filter on those attributes? [duplicate] json json

JavaScript: How to create an Object and filter on those attributes? [duplicate]


Javascript 1.6 (FF, Webkit-based) has built-in Array.filter function, so there's no need to reinvent the wheel.

result = homes.  filter(function(p) { return p.price >= 150000 }).  filter(function(p) { return p.price <= 400000 }).  filter(function(p) { return p.bathrooms >= 2.5 }) etc

for a msie fallback see the page linked above.


Take a look at JSONPath http://code.google.com/p/jsonpath/

Something like jsonPath(json, "$..homes[?(@.price<400000)]").toJSONString() should work.

JAQL also looks interesting for filtering JSON. http://www.jaql.org/


Here you go:

var filteredArray = filter(myBigObject.homes, {    price: function(value) {        value = parseFloat(value);        return value >= 150000 && value <= 400000;    },    num_of_baths: function(value) {        value = parseFloat(value);        return value >= 2.5;    },    num_of_beds: function(value) {        value = parseFloat(value);        return value === 1 || value === 3;    }});

And the filter function:

function filter( array, filters ) {    var ret = [],        i = 0, l = array.length,        filter;    all: for ( ; i < l; ++i ) {        for ( filter in filters ) {            if ( !filters[filter](array[i][filter]) ) {                continue all;            }        }        ret[ret.length] = array[i];    }    return ret;}