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 exist
this[categoryObject.category] = this[categoryObject.category] || [];
// push value
this[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 key
const key = categoryObject.category;
// Appends an array of variables (yAxis data) to one of your arrays using a dynamic key
this[key].concat(categoryObject.data.yAxis);
Solution 3:
You could store the arrays in an object and use the category as the key.
var storage = {
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)"