I have the following jquery/javascript function that gets values from json data and adds them to a variable:
function get_class_classes(data) {
var terms = data.terms, // setup shortcut data path
classList = ''; // setup blank var to add string values to
for (child = 0; child < terms.day.length; child++) {
classList += terms.day[child].slug + ' ';
}
for (child = 0; child < terms.medium.length; child++) {
classList += terms.medium[child].slug + ' ';
}
for (child = 0; child < terms.term.length; child++) {
classList += terms.term[child].slug + ' ';
}
for (child = 0; child < terms.type.length; child++) {
classList += terms.type[child].slug + ' ';
}
return classList;
}
Question:
Is there a cleaner way for me to set this up, meaning, condense all of those for loops into something more succinct?
Here is what I have tried:
function get_class_classes(data) {
var terms = data.terms, // setup shortcut
termsArray = ['day', 'medium', 'term', 'type'],
classList = ''; // setup blank var
for ( i=0; i < termsArray.length; i++ ) {
var currentTerm = termsArray[i];
for (child = 0; child < terms.currentTerm.length; child++) { // loop through each day, add term slug to daylis
classList += terms.currentTerm[child].slug + ' ';
}
}
return classList;
}
This returns the error: Uncaught TypeError: Cannot read property 'length' of undefined
I also moved the var terms = data.terms to the loop, which allowed the function to work, but classList returned filled with 'undefined' rather than the real value.
Sample of data
data is a json object, loosely formatted something the following, which I copied from the console:
terms: Object
day: Array[2]
0: Object
ID: 197
name: "Thursday"
slug: "thursday"
1: Object
medium: Array[1]
0: Object
ID: 200
name: "Painting"
slug: "painting"
/* Continues for variable amount of objects. Same is true for `term` and and `type` */
If you happen to answer and know why my method did not work, an explanation would be great to have for future reference/thought processes.
Thanks!
data.termslooks like?iandchildas global variables, which is usually not what you really want to do. usevar i = 0;andvar child = 0;as the first statements in yourforloops to declare them in the local scope.