Link to home
Create AccountLog in
Avatar of Neil Bradley
Neil BradleyFlag for New Zealand

asked on

Jquery dynamic variable arrays

I am hoping to learn the best way to create and apply dynamic variables into which I can push data (the variables being arrays).

The code below shows 4 variable arrays.

The condition will reside inside an Ajax function into which I will pass either "start" or "end" into the var named "selectionStatus".

I am looking for help with syntax, formatting etc.
Thank you!

let invalid_start = [],labels_start=[],invalid_end = [],labels_end=[];

// selectionStatus will either equal start or end
let selectionStatus='';
      if (foo == bar) {
          labels +"_"+ selectionStatus.push({                                 array data
          });
    } else {
invalid +"_"+ selectionStatus.push({
 array data
          });
}

Open in new window

Open in new window


ASKER CERTIFIED SOLUTION
Avatar of David H.H.Lee
David H.H.Lee
Flag of Malaysia image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Or use square brackets and template literals. I have created a myArrays to not pollute the windows scope

let myArrays = { invalid_start : [],labels_start:[],invalid_end : [],labels_end: [] };
let selectionStatus='start';
if (foo == bar) {
  myArrays[`labels_${selectionStatus}`].push({array data});
} else {
  myArrays[`invalid_${selectionStatus}`].push({array data});
}

Open in new window

Avatar of Neil Bradley

ASKER

The suggestion was extremely helpful and helped to get me across the line.
Thank you!