-1

I have the follwing JSON:

{  
   "_id":"9876567833",
   "result":{  
      "Mercedes":[  
         {  
            "category_name":"Car"
         },
         {  
            "category_name":"Fast"
         }
      ],
      "BMW":[  
         {  
            "category_name":"Car"
         }
      ]
   }

I don't know before "Mercedes" or "BMW" (it could change, this is just for the example). I need to get "Car", "Fast", "Car".

The JSON is in categories So I tried:

    var categoArray = [];
    for(var i =0; i < categories.length; i++){
        for (var idx in categories[i].result) {
               if (categories[i].result[idx].length > 0){
                   categoArray.push(categories[i].result[idx].category_name);
          }
         }
       }

But it doesn't work.

[EDIT] It is not the same :Access / process (nested) objects, arrays or JSON

My question is much more complex

Thanks for your help!

Community
  • 1
  • 1
Jose
  • 1,159
  • 1
  • 9
  • 23
  • How do you want the array to look like? – Amit Joki Oct 31 '14 at 14:47
  • I would like to have in categoArray : Car", "Fast", "Car" – Jose Oct 31 '14 at 14:48
  • @chridam you are right, just edited, thanks – Jose Oct 31 '14 at 14:50
  • You are testing `categories[i].result[idx].length`, which, I assume, you are doing because `categories[i].result[idx]` is an array. Then why are you accessing `categories[i].result[idx].category_name`? Arrays don't have such a property. – Felix Kling Oct 31 '14 at 15:01
  • The thing is I would like the stuff in "category_name": like "Car", "Fast", "Car" – Jose Oct 31 '14 at 15:03
  • @Jose: Is this what you are after: http://jsfiddle.net/abhitalks/3Lx6n2d4/ ? Or this: http://jsfiddle.net/abhitalks/5epj4ywu/ – Abhitalks Oct 31 '14 at 15:07
  • Sorry but nothing happen when I run the jsfiddle – Jose Oct 31 '14 at 15:13
  • @Jose: Check the javascript console. – Abhitalks Oct 31 '14 at 15:15
  • I understand that. I'm just surprised that you seem to know that `categories[i].result[idx]` is an array (otherwise you wouldn't check `length`) and still try to access `category_name` on the *array* instead on one of its *elements*. – Felix Kling Oct 31 '14 at 15:18

2 Answers2

3

You're close, but you need 1 more loop:

var categoArray = [];
for (var i = 0; i < categories.length; i++) {
    for (var key in categories[i].result) {
        for (var j = 0; j < categories[i].result[key].length; j++) {
            categoArray.push(categories[i].result[key][j].category_name);
        }
    }
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

categories[i].result[idx] returns an array, not an object. Therefore, categories[i].result[idx].category_name will be undefined.

Rodney G
  • 4,746
  • 1
  • 16
  • 15