0

The following code returns only the "name" of the first item in the array "category". However I need it to return the "name" value of each item in the array.

What am I missing?

function loadCategories(id){
   for (var i = 0; i<folder.grades.models.length; i++){
      if(folder.grades.models[i].attributes.entityid==id) {
         return folder.grades.models[i].attributes.categories.category[i].name;
      }
   }
}
1
  • Why are you using the same i as an index into both models and category? Commented Feb 27, 2013 at 19:24

3 Answers 3

1
function loadCategories(id){
   var items = folder.grades.models;
   for (var i = 0; i<items.length; i++){
      if(items[i].attributes.entityid==id) {
         return items[i].attributes.categories.category.map(function(c) {
            return c.name;
         });
      }
   }
   return [];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Curious.. If I wanted to also get another property such as the "age" of the category and not only the name, would I need to write another function or for loop within the current function?
You could replace return c.name; with return [c.name, c.age];
1

return exits the function, you should add all names to an array and then return that array

function loadCategories(id){
   var names = [];
   for (var i = 0; i<folder.grades.models.length; i++){
      if(folder.grades.models[i].attributes.entityid==id) {
         names[i] = folder.grades.models[i].attributes.categories.category[i].name;
      }
   }
   return names;
}

Comments

0

Return statements break out of functions, so once it hits that return statement, the function is over. If you want all of the names of the categories that match entity id:

function loadCategories(id){
   var result = [];
   for (var i = 0; i<folder.grades.models.length; i++){
      if(folder.grades.models[i].attributes.entityid==id) {
         for (var j = 0; j < folder.grades.models[i].attributes.categories.category.length; ++j) {
            result.push(folder.grades.models[i].attributes.categories.category[j].name);
         }
      }
   }
   return result;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.