12

I am looking to iterate 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 row into different functions based on the label. I am trying to figure out if a multidimensional array is the best way to go.

0

3 Answers 3

18
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.

Sign up to request clarification or add additional context in comments.

Comments

13

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

Comments

2

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 ;)

Comments

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.