简体   繁体   中英

Underscore.js `filter` not working

I have the following code snippet I use to choose which suburbs from a list the user has selected (with irrelevant code omitted):

var allSuburbsList = new Array([{"SuburbID":1,"SuburbAreaID":3,"SuburbName":"Alberante","SuburbActive":true,"Area":null,"Agents":[]},{"SuburbID":4,"SuburbAreaID":3,"SuburbName":"Alberton North","SuburbActive":true,"Area":null,"Agents":[]}]);

var a3burbs = _.filter(allSuburbsList, function(s) { return s.SuburbAreaID === 3; }); 
// 3 is a test value. All the test suburbs so far fall under area no. 3.

With this filter, a3burbs comes out as an empty array, [] . If I cheat and make the filter:

var a3burbs = _.filter(allSuburbsList, function(s) { return true; }); 

then a3bubrs comes out an exact copy of allSuburbsList , with all suburbs included. What could I be doing wrong? I'm using the same syntax as indicated on the Underscore.js home page.

Btw, would the way I populate allSuburbsList from a viewmodel array property have anything to do with this:

var allSuburbsList = new Array(@Html.Raw(JsonConvert.SerializeObject(Model.AllSuburbs)));

Just for interest, my first attempt was the hideous code below, but it worked:

var a3burbs = [];
@{for (var i = 0; i < Model.AllSuburbs.Length; i++) {
    @:if (allSuburbsList[@i].SuburbAreaID === 3) {
        @:a3burbs.push(allSuburbsList[@i]);
    };
};

You're creating a new array and passing in an array.

Change it to

var allSuburbsList = [{"SuburbID":1,"SuburbAreaID":3,"SuburbName":"Alberante","SuburbActive":true,"Area":null,"Agents":[]},{"SuburbID":4,"SuburbAreaID":3,"SuburbName":"Alberton North","SuburbActive":true,"Area":null,"Agents":[]}];

Using new Array([{}]) , you are creating an array inside another array. Just instantiate that without new Array()

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