2

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"
     },
Charlie
  • 22,886
  • 11
  • 59
  • 90
esteves67
  • 19
  • 3

2 Answers2

2

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);
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
2

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;
Charlie
  • 22,886
  • 11
  • 59
  • 90
  • 1
    `x: [{y: [{z: 'foo'}]}]` to access z `x[0].y[0].z` – Charlie Jul 31 '20 at 08:23
  • 1
    Thank you so much Charlie! Working beautifuly! Thank you!!! Im sorry that i cant mark two answers with the green check mark, sorry =( – esteves67 Jul 31 '20 at 08:25
  • 2
    No worries. It doesn't matter which one you choose - as long as you learned something and it solved your problem. – Charlie Jul 31 '20 at 08:43