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

2
  • 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. Commented Sep 7, 2013 at 16:02
  • FYI, when you use for (var <variable> in <array>), <variable> will be set to the array indexes, not the values -- it's not like PHP foreach Commented Sep 7, 2013 at 16:14

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I've learned on SO that "I'm new to <language>" actually means "I'm new to programming", so referring them to "like in any other language" doesn't actually help them.
I'm not saying your answer was bad, just trying to give you the benefit of my experience to help you in the future.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.