Trunk collection, countBy errors

I have a collection that I want to group by counting the same values ​​in my attribute. So I do this:

_.countBy(T.collection,function(model){ return model.get('text') }) 

where the attribute is a string. This string can have letters (Az), ':' and '_' ( underscore ). It has no spaces.

But the code throws

Unable to call the 'get' method from undefined.

I also tried using

 T.collection.countBy(function(model){ return model.get('text') }) 

but he throws

[Object Object] does not have a 'countBy' method

+4
source share
2 answers

countBy not one of the Underscore methods mixed with collections , so as you saw, this will not work:

 T.collection.countBy(function(model){ return model.get('text') }); 

And the collection is not an array, so this will not work either:

 _.countBy(T.collection,function(model){ return model.get('text') }); 

When you do this, model will not be the model in the collection, it will be one of the property values ​​of the T.collection object; for example this:

 _({where: 'is', pancakes: 'house?'}).countBy(function(x) { console.log(x); return 0 });​​​ 

will give you is and house? in the console.

However, T.collection.models is an array, an array of models. This means that this should work:

 _.countBy(T.collection.models, function(model) { return model.get('text') }); 

I would recommend adding this as a method to your collection so that outsiders can not get around the property of the models collection.

+7
source

I can make 2 sentences:

1: somewhere in the collection "model" undefined. Therefore, when you do model.get ('text'), it throws an error, because you cannot run the method with the variable undefined. Perhaps your function should be:

 _.countBy(T.collection,function(model){ return model ? model.get('text') : ''; // or maybe a null, depending on what you want }); 

2: for debugging, use the firebug console to verify that the model values ​​are ie

 _.countBy(T.collection,function(model){ console.log('model', model); return model ? model.get('text') : ''; }); 

Hope this helps

0
source

Source: https://habr.com/ru/post/1442028/


All Articles