-4

looping through this object and displaying the messages in separate div received from different users. How to do this.Please Help.I am new to JSON,Jquery and Javascript

[
Object { id="1", fromuser="1", touser="4", msg="hi"}, 
Object { id="2", fromuser="2", touser="4", msg="hello"}, 
Object { id="3", fromuser="2", touser="4", msg="hru?"},
Object { id="4", fromuser="3", touser="4", msg="hru?"},
Object { id="5", fromuser="1", touser="4", msg="hru?"} 
]

------------ ------------ ------------
|fromuser:1| |fromuser:2| |fromuser:3|
|msg:hi    | |msg:hello | |msg:hru?  |
|msg:hru?  | |msg:hru?  | |          |
------------ ------------ ------------
LoneRanger
  • 665
  • 13
  • 31
  • 1
    What is your approach? Just asking for code is not what StackOverflow is meant for. – Zim84 Feb 01 '14 at 10:27
  • possible duplicate of [How to parse JSON in JavaScript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) – phyrox Feb 01 '14 at 10:34
  • Also quite hard to understand. You could at least help folks by commenting below answers :/ –  Feb 01 '14 at 18:11

2 Answers2

2

You can use Jquery

var yourObject = [
    { id = "1", fromuser = "1", touser = "4", msg = "hi" }, 
    { id = "2", fromuser = "2", touser = "4", msg = "hello" }, 
    { id = "3", fromuser = "2", touser = "4", msg = "hru?" }, 
    { id = "4", fromuser = "3", touser = "4", msg = "hru?" }, 
    { id = "5", fromuser = "1", touser = "4", msg = "hru?" }
];
$.each(yourObject, function () {
    $um = $('#usermesage' + this.fromuser);
    // create new container if doesn't existes.
    if ($um.length == 0) {
        $um = $('<div />', {
            'id': 'usermesage' + this.fromuser
        });
        $um.appednTo('body');
    }
    $um.append($('<div />', {
        'class': 'line'
    }).append(
        $('<div />', {
            text: "msg" + this.msg
        });
    ));
});
Erik Simonic
  • 457
  • 3
  • 13
1

For each item you need to check if it is an object's 'key' - property.

for (var property in object) {
    if (object.hasOwnProperty(property)) {
        //
    }
}
Kostadin
  • 405
  • 3
  • 14