2

I have two arrays:

  • one with categories
  • one with datarecords

Every data record belongs to a specific category.

With every use of a filter (e.g. searchfield) on the datarecords, I want to add the total count of records per category to each category-object, so I can display them on every tab-pane (e.g. text: Algemeen, value: 'general, countFiltered: 2)

I made a fiddle for this.

Till now I get no count-filtered, locally I get a constant error corresponding to line 78 in my fiddle:

Uncaught (in promise) Type Error: Cannot read property '0' of undefined

How can I achieve this?

2
  • 1
    That kind of error that has the worst description ever? Commented Jan 5, 2016 at 20:29
  • 1
    I think the question actually makes sense, you just have to read it slower. When he searches he wants the number of results for each category to show up on the pane of that category, kind of like a facebook badge. Commented Jan 5, 2016 at 20:40

1 Answer 1

7

this isn't what you think it is here:

var filtered = results.filter(function (results) {
    return (results.category.toLowerCase() == this.categories[cat].value.toLowerCase());
});

You can either pass in a thisArg to filter:

var filtered = results.filter(function (results) {
    return (results.category.toLowerCase() == this.categories[cat].value.toLowerCase());
}, this);

or in ES6 you can use an arrow function:

var filtered = results.filter(
    results => results.category.toLowerCase() == this.categories[cat].value.toLowerCase() 
);
Sign up to request clarification or add additional context in comments.

5 Comments

Solved it! Why do you need to pass a thisArg? Does it apply to the results in my vue-model?
@BFlyDesign A closure has access to outer-scoped variables only if they aren't shadowed by it's own variables, but every time a function is called in Javascript the value of this inside it is set, so unlike other variables this is always shadowed. If you pass in a second argument you are telling filter that you want this inside your callback to be whatever you passed in. In your case you passed in this from outside the callback, so even though the callback still has it's own this shadowing the outer this, it refers to the same object.
what do I need to change in my fiddle to let it automaticaly update the count when using the searchfield?
@BFlyDesign I'd never heard of Vue until now, so I'm not sure if this is the best way, but it seems like you just need to call tokens.countFiltered from your filter. See the update here: jsfiddle.net/ukgs5dy7/9
not completely working as intended but you've put me on the right track! Thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.