Skip to content Skip to sidebar Skip to footer

How To Simplify Else-if Statements Where Text String Evaluation Has The Same Name As Array Getting Appended To? (javascript)

The following is a series of else-if statements, where once evaluated, appends data to an array with the same name as the hard-coded strings in the evaluation statement. I know the

Solution 1:

Why not use a dynamic approach, and omit local variables which have nothing to do with this.

categoryObject.data.yAxis.forEach(element => {
    // create array, if not existthis[categoryObject.category] = this[categoryObject.category] || [];
    // push valuethis[categoryObject.category].push(element);
});

Solution 2:

Since your category key corresponds to your array variable names you can use a dynamic key based on the category.

Furthermore, you can use concat to copy all the values in your yAxis data into your arrays without the need to loop through each item.

// Stores the dynamic keyconst key = categoryObject.category;

// Appends an array of variables (yAxis data) to one of your arrays using a dynamic keythis[key].concat(categoryObject.data.yAxis);

Solution 3:

You could store the arrays in an object and use the category as the key.

varstorage= {
  name: [],
  name2: [],
  name3: [],
  name4: [],
  name5: [],
  name6: [],
  name7: [],
  name8: [],
  name9: [],
  name10: [],
  name11: [],
  name12: [],
  name13: []
}
categoryObject.data.yAxis.forEach(element=> {
  //console.log('y:' + element);
  storage[categoryObject.category].push(element);
});

Post a Comment for "How To Simplify Else-if Statements Where Text String Evaluation Has The Same Name As Array Getting Appended To? (javascript)"