0

I'm fairly new to JavaScript. I used this to Jasonify an array:

    <script>
         var numobjects = jQuery.parseJSON('{{result|jsonify}}');
    </script>

and the result is correct:

    jQuery.parseJSON
        ('[
        {"category": "Perfumes", "comments": [good]}, 
        {"category": "Perfumes", "comments": [ok]}, 
        {"category": "Perfumes", "comments": [I like it!]}
        ]');

I don't now how to get the "comments" object using JavaScript. I tried something like this: Getting JavaScript object key list

    <script>
        var numobjects = [jQuery.parseJSON('{{result|jsonify}}')];
        var com = [];
          for (var comments in numobjects) com.push(comments);
            {
               console.log("total " + com.length + " comments: " + comments);
            }
   </script>

Thank you for the help

Community
  • 1
  • 1
user2755801
  • 43
  • 1
  • 3
  • 9
  • OK - you need to learn the developer tools. A absolute must to learn jQuery / javascript. If you query the object in the dev tools console, you will see how to drill down into the objects. – Greg Sep 07 '13 at 16:02
  • FYI, when you use `for (var in )`, `` will be set to the array indexes, not the values -- it's not like PHP `foreach` – Barmar Sep 07 '13 at 16:14

1 Answers1

2

First, you don't need to create another array here

var numobjects = [jQuery.parseJSON('{{result|jsonify}}')];

you need just parse your json:

var numobjects = jQuery.parseJSON('{{result|jsonify}}');

second, iterate through your array like in any other language and get your data via dot-notation:

var comments = [];
for (var i = 0; i < numobjects.length; i++) {
   comments.push(numobjects[i].comments);
};
alert(comments.length);
Tommi
  • 3,199
  • 1
  • 24
  • 38
  • I've learned on SO that "I'm new to " actually means "I'm new to programming", so referring them to "like in any other language" doesn't actually help them. – Barmar Sep 07 '13 at 16:09
  • I'm not saying your answer was bad, just trying to give you the benefit of my experience to help you in the future. – Barmar Sep 07 '13 at 16:12
  • I guess both you guys have a point, and I appreciate for the help. In this case I am new to programming considering that css and html isn't really taken as programming, although I dont have the knowledge, it is being built mostly on iterations of what I have been doing and reading. I will try to use the above and get back to you guys. tks @Tommi – user2755801 Sep 07 '13 at 16:44