0

I am a beginner to jQuery and although it seems like an easy question I just don't seem to have the terminology to look it up on Google - have tried everything...

I am trying to do some Array parsing as a function and have put this thing together by looking it up on the web. I would like it to count the number of objects in an array where the "key" and "item" are the same. I already know that the key is wid and it is called via the key.

function countmeta(array, thekey, item) {
    var count = 0;
    var tkey = 'wid';
    $.each(array, function(i, v) { 
      if (v.thekey == item) 
        count++; 
    });
    return count;
} 

If I set it manually it works perfectly:

$.each(array, function(i, v) { 
  if (v.wid == item) 
    count++; 
});

I also tried stuff like

var tkey = 'wid';
var tkey = "wid";

and

var tkey = thekey;
$.each(array, function(i, v) { 
  if (v.tkey == item) 
    count++; 
});

What am I doing wrong? I obviously have a gap in my understanding of what type of variable or string the wid represents in v.wid. Please help.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
clfr98ad
  • 1
  • 2
  • You need to use bracket notation when attempting to access the key of an object by variable. In this case `v[tkey]`. I would also suggest using the native `filter()` method and returning the length of the resulting array instead of using `$.each()`. It should be faster, doesn't rely on jQuery, and doesn't use an extra variable. – Rory McCrossan Nov 19 '19 at 09:20
  • 1
    So simple. Thanks very much! – clfr98ad Nov 19 '19 at 09:28

0 Answers0