如何从Angularjs中的JSON获取某个属性中的最后一个值

时间:2016-03-08 14:34:45

标签: javascript android angularjs json cordova

我的app.js中有这个代码,用于在我的应用程序中发送聊天和阅读聊天

$scope.messageshistory = {};
$scope.tmp = {};

    // send message
    $scope.sendMessage = function(){
        $scope.messages = {
            from      : $scope.datauser['data']['_id'],
            fromname  : $scope.datauser['data']['nama'],
            to        : $scope.tmpuserid,
            message   : $scope.tmp['sendmessage'],
            time      : moment()
        };
          //event emit message
        socket.emit('message',$scope.messages,function(callback){       
          if(!callback['error']){
                 $scope.messages['time'] = moment($scope.messages['time']).format('DD-MMMM-YYYY HH:MM');


                if ($scope.messageshistory.hasOwnProperty($scope.tmpuserid)){ //yg di json yg paling awal
                    $scope.messageshistory[$scope.tmpuserid].push($scope.messages);
                }else{
                    $scope.messageshistory[$scope.tmpuserid] =   [];
                    $scope.messageshistory[$scope.tmpuserid].push($scope.messages);
                }
                $scope.tmp['sendmessage'] = '';
          }else{
               var msg = callback['error'];
                navigator.notification.alert(msg,'','Error Report', 'Ok');
            }

            $scope.$apply();
        });
    };
      //event read message
    socket.on('message', function (data) {

        window.plugin.notification.local.add({
            id        :   moment(),
            title     :   data['fromname'],
            message   :   data['message'].substr(0,20) + ' ...',
            led       : 'A0FF05',
            json      :   JSON.stringify({ routes:'chat', nama :data['fromname'],from:data['from'] })
        });
        data['time'] = moment(data['time']).format('DD-MMMM-YYYY HH:MM');
        if ($scope.messageshistory.hasOwnProperty(data['from'])){
            $scope.messageshistory[data['from']].push(data);
        }else{
            $scope.messageshistory[data['from']] =   [];
            $scope.messageshistory[data['from']].push(data);
        }

        for(var i = 0; i<= $scope.datauser['data']['friends'].length; i++){
            if($scope.datauser['data']['friends'][i]['userid'] == data['from']){
                $scope.datauser['data']['friends'][i]['ischat'] = true;
                break;
            }
        };
        $scope.$apply();
    });

我的问题是如何从$scope.messageshistory获取邮件属性中的最后一个值,因为$scope.messages用于发送邮件,而$scope.messageshistory是为了保留邮件聊天记录。这是聊天活动图片:

enter image description here

仅从此活动开始,$scope.messageshistory会将JSON中的数据保存为:

{
    "5512": [{
        "from": "561c",
        "fromname": "ryan",
        "to": "5512",
        "message": "hey",
        "time": "18-Maret-2016 21:03"
    }, {
        "from": "5512",
        "fromname": "sasa",
        "to": "561c",
        "message": "hello",
        "time": "18-Maret-2016 21:03",
        "_id": "593s"
    }]
}

我从使用angular.toJson($scope.messageshistory)获得此值,如果聊天活动仍在进行,此数组将始终加起来。我打算从$scope.messageshistory获取message属性中的最后一个值是在我的应用程序中使用Text-to-Speech功能。这是代码:

$scope.speakText = function() {

    TTS.speak({
           text: **this the place for the code**,
           locale: 'en-GB',
           rate: 0.75
       }, function () {
          // handle the success case
       }, function (reason) {
           // Handle the error case
       });
  };

它会读取$scope.messageshistory中的最后一条消息。那么,我必须编写哪些代码来获取最后一个值?

2 个答案:

答案 0 :(得分:0)

假设历史对象中的键是升序数,并且考虑到W3C未指定对象中键的顺序,则必须执行以下操作:

  1. 获取所有密钥
  2. 找到“最新”(因此最大的数字)
  3. 抓取它
  4. 所以你可以做例如

    var keys = Object.keys($scope.messagehistory);
    keys.sort (function (a, b) {
      return a - b;
    });
    var result = keys[keys.length - 1];
    

答案 1 :(得分:0)

您必须执行以下操作:

var msgs = $scope.messageshistory[$scope.tmpuserid]
var yourLastMessage = msgs[msgs.length-1].message
// you could also add a quick check so you don't get
// an error if the messages array is emtpy :
// var yourLastMessage = (msgs && msgs[msgs.length-1] ? msgs[msgs.length-1].message : null)

修改

根据您的评论做出一些解释:

var msgs = $scope.messageshistory[$scope.tmpuserid]
// msgs is now an Array containing Objects
// [{message : 'xxx'},{message : 'yyy'}]
// we take the last entry of the msgs Array (msgs.length-1)
// so msgs[msgs.length-1] is the last object ({message : 'yyy'})
// and finally we take the 'message' property' of that object:
var yourLastMessage = msgs[msgs.length-1].message