简体   繁体   中英

Filter JSON objects based on condition in Backbone

I have the below JSON response. In Backbone I want to filter some objects(names) from the array

For example - Here i need to loop only 'Jack','Mcd' objects(names. Need to get only Jack and Mcd names from arrary.

Can anyone give me any ideas to implement?

resultstest = {
"r": [{
    "IsActive": false,
    "re": {
        "Name": "Depo"            
    },
    "Expire": "Oct8, 2013",
    "Clg": [{
        "Name": "james",
        "Rate": 0.05
    }, {
        "Name": "Jack",
        "Rate": 0.55
   }, {
        "Name": "Ander",
        "Rate": 0.46
   }, {
        "Name": "Mcd",
        "Rate": 0.01,
    }],
},
{
    "IsActive": false,
    "re": {
        "Name": "Depo"
    },
    "Expire": "Oct8, 2013",
    "Clg": [{
        "Name": "james",
        "Rate": 0.05
    }, {
        "Name": "Jack",
        "Rate": 0.55
   }, {
        "Name": "Mcd",
        "Rate": 0.01,
    }],
},
{
    "IsActive": false,
    "re": {
        "Name": "Depo"
    },
    "Expire": "Oct8, 2013",
    "Clg": [{
        "Name": "james",
        "Rate": 0.05
    }, {
        "Name": "Jack",
        "Rate": 0.55
   }, {
        "Name": "Mcd",
        "Rate": 0.01,
    }],
}]
};    

loadjson = function (input) {
        if (_.isArray(input)) {
            var collection = new CompeCollection();
            _.each(input, function (modelData) {
                ....
            });
            return collection;
        }
            };
var tablesResult = loadjson(resultstest.r[0].Clg); // can we filter here like resultstest.r[0].Clg(!="james" && !="Ander")

Is there any array method to filter those objects while passing to loadjson function? Any help would be helpful.

Thanks

You can use Array.filter method of arrays supported in modern browsers. For compatibility of old browsers, you can use _.filter ( http://underscorejs.org/#filter ).

So your code would be like,

var tablesResult = loadjson(_.filter(resultstest.r[0].Clg, function(clg) { return (clg.name !="james" && clg.name !="Ander"); }))

To DRY your code, you can event create this filter function separately and simple reference it here. Like,

var collegeFilter = function(clg) { return (clg.name !="james" && clg.name !="Ander"); }
...
var tablesResult = loadjson(_.filter(resultstest.r[0].Clg, collegeFilter));

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