LearningAsIGo
LearningAsIGo

Reputation: 1311

Get Length of Object when Key contains two part identifier

I am working on node.js at my work and trying to access data from table. Using an internally developed node library, I am able to make that call and get results back in 'res'. As usual, 'res' is an object. Records from table are in the following format:

{
random.key1 : some_value
random.key4 : some_value
Row[0].col1 : some_value
Row[0].col2 : some_value
Row[1].col1 : some_value
Row[1].col2 : some_value
}

As you can see, result contains not just rows but some additional elements that node library adds into response. I want to count only those keys that have 'col1' in their 'key'.

For example, above example should give count = 2 since there are two keys with 'col1' in it. I am doing something like this:

var getLength = function(input) {
var count = 0;
for (var key in input) {

    if (input.hasOwnProperty(key) && key.indexOf('col1') == 0)
    {
        count ++
    }
}
return count;

}

Can someone please tell me best way to get right count?

Upvotes: 0

Views: 38

Answers (1)

Richard Walton
Richard Walton

Reputation: 4785

function countKeysContaining(obj, str) {
   var count = 0;

   for(var key in object) {
      if(key.split('.').indexOf(str) != -1) {
          count++;
      }
   }


   return count;
}

Upvotes: 1

Related Questions