Iterate over a list of values using javascript
I am looking for iterating over a list of values using javascript.
I have a list like this
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
My goal is to pass each line to different functions based on the label. I am trying to figure out if a multidimensional array is appropriate.
+3
source to share
2 answers
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 can define a function matchesLabel
, it must return true if an element should be passed to your function.
+11
source to share
If you want to make it more professional, 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 the context you want (a typical window scenario ) and pass some arguments. Hope this helps;)
+2
source to share