Debarun Pal Debarun Pal - 3 months ago 8
JSON Question

Using Angular to iterate through a JSON and get the result

I have this following JSON format:

[{
"-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


}]

Now I am using Angular to retrieve the part of the data that I need from the JSON Array.

The Angular Code is:

$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);
});
});


The Data that I want to retrieve from the JSON is:

{
"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"


}

So, basically I want everything from the JSON Array except the message id key that starts with -KQV...

But it is always returning Key: 0 Value: [object Object].

Can anyone help me out with a solution?

Answer

You can use the Object.keys(object).foreach() syntax to iterate through each key of the object and check if the object name begins with -KQV. If so, use that object. That will get you the specific part of each array that you want. Here, I'm printing it to the console and pushing it into the $scope.user_message array.

$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]);
        }
    });
}