Iterate over a list of values using javascript

var list = [
   {"Label": "A", "value": "Test", "Count": 4},
   {"Label": "B", "value": "Test2", "Count": 2},
   {"Label": "C", "value": "Test3", "Count": 4},
   {"Label": "D", "value": "Test4", "Count": 1},
   {"Label": "C", "value": "Test5", "Count": 1}
]

for(var i = 0, size = list.length; i < size ; i++){
   var item = list[i];
   if(matchesLabel(item)){
      someFunction(item);
   } 
}

You get to define the matchesLabel function, it should return true if the item needs to be passed to your function.


well it's been 8 years but today you can use for ... of

const array1 = ['a', 'b', 'c'];

for (const element of array1) {
  console.log(element);
}

source : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of


If you would like to make it more pro, you can use this function

function exec(functionName, context, args )
{
    var namespaces = functionName.split(".");
    var func = namespaces.pop();

    for(var i = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
    }

    return context[func].apply(this, args);
}

This function allows you to run it in context you want (typical scenario is window context) and pass some arguments. Hope this helps ;)

Tags:

Javascript