-1

I have this JSON array with a lot of person data every one with a type like "hr" or "accounting".

the JSON array looks like this:

{
    "0": {
        "id": "2",
        "name": "blabla",
        "type": "hr"
    },
    "1": {
        "id": "3",
        "name": "bub",
        "type": "hr"
    },
    "2": {
        "id": "4",
        "name": "ula",
        "type": "accounting"
    },
    "3": {
        ...
    }
}

I want to display them in an ul like this:

<ul>
   <li><p>hr</p>name: blabla<p></li>
   <li><p>hr</p>name: bub<p></li>
   <li><p>hr</p>......</li>
</ul>
<ul>
   <li><p>accounting</p>name: ula<p></li>
   <li><p>accounting</p>......</li>
</ul>

but i have no clue how to separate the JSON array or how to properly loop through it to display it like that.

arserbin3
  • 6,010
  • 8
  • 36
  • 52
Frank
  • 155
  • 3
  • 13

2 Answers2

2

this will basically do what you want for one department. You can use it for each department by putting an if in the each loop and checking it against value.type

var new_html = "<ul>";
$.each('name_of_json_array', function(key, value){
    new_html+="<li><p>"+value.type+"</p><p>name: "+value.name+"</p></li>";
});
new_html+="</ul>";
$('#some_container_element').append(new_html);
Rooster
  • 9,954
  • 8
  • 44
  • 71
2

Try this:

<!DOCTYPE html>
<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    </head>
    <body>
        <div class="container"></div>
        <script>
        var json={
            "0": {
                "id": "2",
                "name": "blabla",
                "type": "hr"
            },
            "1": {
                "id": "3",
                "name": "bub",
                "type": "hr"
            },
            "2": {
                "id": "4",
                "name": "ula",
                "type": "accounting"
            }
        };

        var previous_type=json[0].type;
        var _html="<ul>";

        $.each(json, function(index,key) {
            if (previous_type!=key.type) {
                _html+="</ul><ul>";
            }
            previous_type=key.type;
            _html+="<li><p>"+key.type+"</p><p>name: "+key.name+"</p></li>";
        });
        _html+="</ul>";
        $('.container').html(_html);
        </script>
    </body>
</html>

It creates a new ul for every different type.

Output of container:

<div class="container">
    <ul>
        <li>
            <p>hr</p>
            <p>name: blabla</p>
        </li>
        <li>
            <p>hr</p>
            <p>name: bub</p>
        </li>
    </ul>
    <ul>
        <li>
            <p>accounting</p>
            <p>name: ula</p>
        </li>
    </ul>
</div>
Dave Chen
  • 10,887
  • 8
  • 39
  • 67
  • thanks dave works like a charm... almost like what i had but i missed the most important part the if loop... both thumps up from me – Frank Jun 27 '13 at 01:12