使用Angular迭代JSON并获得结果

Using Angular to iterate through a JSON and get the result

本文关键字:结果 JSON Angular 迭代 使用      更新时间:2023-09-26

我有以下JSON格式:

[{
"-KQVfnf1ZCml7dZ1dZAC": {
    "content": {
        "data": "New Order",
        "type": "text/plain"
    },
    "conversation_id": "990",
    "is_admin": false,
    "is_announce": false,
    "is_deleted": false,
    "message_id": "9694",
    "sender": {
        "name": "Paras",
        "user_id": "285"
    },
    "sent_at": "1472648381032"
},
"-KQVgEHps9L3l80nmkWb": {
    "content": {
        "data": "New Shipment",
        "type": "text/plain"
    },
    "conversation_id": "990",
    "is_admin": false,
    "is_announce": false,
    "is_deleted": false,
    "message_id": "9694",
    "sender": {
        "name": "Paras",
        "user_id": "285"
    },
    "sent_at": "1472648431073"
},
"created_at": "1472647272113",
"$id": "messages",
"$priority": null

}]

现在我正在使用Angular从JSON数组中检索我需要的那部分数据。

Angular的代码是:
$scope.user_message = [];
   $scope.user_content = [];
   angular.forEach($scope.messages, function(value, key){
     $scope.user_message.push(value);
     angular.forEach($scope.user_message, function(value, key){
       $scope.user_content.push(value[key]);
       console.log($scope.user_content);
     });
   });

我想从JSON中检索的数据是:

{
"content": {
    "data": "New Order",
    "type": "text/plain"
},
"conversation_id": "990",
"is_admin": false,
"is_announce": false,
"is_deleted": false,
"message_id": "9694",
"sender": {
    "name": "Paras",
    "user_id": "285"
},
"sent_at": "1472648381032"

}

基本上,我想要JSON数组中的所有内容除了消息id键以-KQV…

但是它总是返回Key: 0 Value: [object object].

谁能给我一个解决方案?

您可以使用Object.keys(object).foreach()语法遍历对象的每个键,并检查对象名称是否以-KQV开头。如果是,使用该对象。它会得到你想要的每个数组的特定部分。在这里,我将它打印到控制台并将其推入$scope.user_message数组。

$scope.user_message = [];
for (var i=0; i < $scope.messages.length; i++) {
    Object.keys($scope.messages[i]).forEach(function(key,index) {
        if (key.substr(0, 4) == '-KQV') {
            console.log($scope.messages[i][key]);
            $scope.user_message.push($scope.messages[i][key]);
        }
    });
}

这个更短,但假设JSON数组的第一个元素总是包含消息:

//var j = JSON.parse(...)
for (key in j[0]) {
  if (j[0].hasOwnProperty(key) && (key != "created_at") && (key != "$id") && (key != "$priority")) {
    console.log(j[0][key]);
  }
}

它还将我们确定不是消息的键('created_at'等)列入黑名单,而不是将那些以特定字符串('-Kv')开头的键列入白名单,这可能最终会改变。

不太确定您想要的是什么,如果可以用更多的示例消息扩展消息数组并提供预期的输出,那就太好了。这个版本的代码将把每个消息中的所有对象存储到$scope中。user_content(它没有检查'KQV'):

$scope.user_message = [];
   $scope.user_content = [];
   angular.forEach($scope.messages, function(value, key){
     $scope.user_message.push(value);
     angular.forEach(value, function(value1, key1){
       if (value1 === null || typeof value1 !== 'object') return;
       $scope.user_content.push(value1);
     });
   });
 console.log($scope.user_content); 

小提琴:http://jsfiddle.net/b2gy2yr1/

我还建议您查看lodash -它使这类任务更容易:https://lodash.com/docs/4.15.0