0

i have this code:

$.getJSON('newMessageDetails', function (json)
{
    var old_id = document.getElementById("td_id").value;
    var messages_count = Object.keys(json).length;           
    console.log(messages_count);
    console.log(json);
    last_id = json[messages_count]["msgId"];

});

the json[messages_count]["msgId"] gives undefined in the console??

my newMessageDetails:

public function executeNewMessageDetails(sfWebRequest $request)
{  
    $profile_id = $this->getUser()->getAttribute('profile_id','zero');  
    $new_msgs = RcMessageBoxTablePeer::getNewMessages($profile_id);
    $hr=2;
    $i=1;
    if (count($new_msgs) >= 1)
    {
        foreach ($new_msgs as $row)
        {
           $date = $row->getCreatedAt();
           //$cd = strtotime($date);
           //$newdate = date('Y-m-d H:i:s', mktime(date('h',$cd), date('i',$cd), date('s',$cd), date('m',$cd), date('d',$cd), date('Y',$cd)));
           $subject = $row->getSubject();
           $message = $row->getMessage();
           $from = $row->getProfileIdFrom();
           $id = $row->getId();
           $uc_record = RcProfileTablePeer::getById($from);
           $uc_from = $uc_record->getUniqueCode();
           $output[$i] = array("td_date" => $date, "td_subject" => $subject, "td_from" => $uc_from, "td_message" => $message, "msgId" => $id , "i" => $i);
           $i++;
        }
        return $this->renderText(json_encode($output));
    }
}

console.log(json) gives:

5
list:98
Object
543: Object
544: Object
545: Object
546: Object
547: Object
i: 1
msgId: 547
td_date: "2011-11-29 11:33:05"
td_from: "CHARLIE000RC"
td_message: "tooltip show message test 2 id 547"
td_subject: "Freechat message"

can some-one explain please? dont know what im doing wrong though thanks

charlie_cat
  • 1,830
  • 7
  • 44
  • 73
  • possible duplicate of [Length of an object filled with objects?](http://stackoverflow.com/questions/5545426/length-of-an-object-filled-with-objects) – Quentin Nov 29 '11 at 08:29

3 Answers3

1

Objects don't have a length property. try this.

var obj = jQuery.parseJSON(json);

obj.length();

or you can try this.

Object.keys(json).length;  
erimerturk
  • 4,230
  • 25
  • 25
0

If you would like a count of all keys you could rewrite it to this:

$.getJSON('newMessageDetails', function (json)
{
    ...;
    var messages_count = Object.keys(json).length;           
    console.log(messages_count);
});
0

you should just iterate through the object and count . Thats the only way you can really know how many 'meaningful' objects you have in your object.

kommradHomer
  • 4,127
  • 5
  • 51
  • 68