How to filter deep nested data? - Javascript JSON

Viewed 197

I need to filter a JSON data between three values, I got two values working which is "timestamp" that are not nested/deep, but one value is nested which is "fromMe".

I have access to the "timestamp" value because its not nested, but I cant get it working to access the lastMsg -> id -> fromMe.

Javascript code

         var filterMessages = chats_ativo.filter(function(x){ 
            return x.timestamp >= variable1 && x.timestamp <= variable2; /* working */
            return x.timestamp >= variable1 && x.timestamp <= variable2 && x.lastMsg.id.fromMe == false; /* not working */
         });

JSON data - console log (deleted some personal info)

  "id": {
   "server": "c.us",
   "user": "phonenumber",
   "_serialized": "phonenumber@c.us"
  },
  "name": "Name",
  "isGroup": false,
  "isReadOnly": false,
  "unreadCount": 0,
  "timestamp": 1596167676,
  "archived": false,
  "lastMsg": [
   {
    "id": {
     "fromMe": false,
     "remote": {
      "server": "c.us",
      "user": "phonenumber",
      "_serialized": "phonenumber@c.us"
     },
2 Answers

This approach should work, since the lastMsg property is an array, I'd note that we should also ensure that lastMsg exists and the properties accessed are available.

You could also consider having a look at the lodash get function, this can be very useful for accessing nested properties.

let chats_ativo = [{ "id": { "server": "c.us", "user": "phonenumber", "_serialized": "phonenumber@c.us" }, "name": "Name", "isGroup": false, "isReadOnly": false, "unreadCount": 0, "timestamp": 1596167676, "archived": false, "lastMsg": [ { "id": { "fromMe": false, "remote": { "server": "c.us", "user": "phonenumber", "_serialized": "phonenumber@c.us" } } }] }];

var variable1 = 1596167676;
var variable2 = 1596167676;

var filterMessages = chats_ativo.filter(function(x) { 
    return x.timestamp >= variable1 && x.timestamp <= variable2 && x.lastMsg[0].id.fromMe == false; 
});
     
console.log("Filtered messages:", filterMessages);

The lastMsg is an array. It needs to be accessed by index.

Assuming it has only one object as an element.

return x.timestamp >= variable1 && x.timestamp <= variable2 && x.lastMsg[0].id.fromMe == false;
Related