Filtering deep nested data in Javascript JSON: A guide

I have a JSON data that needs to be filtered based on three values. I have managed to filter based on two values, "timestamp" which is not nested, but I am struggling with the nested value "fromMe".

While I can easily access the "timestamp" value as it is not nested, I am unable to filter based on x.lastMsg.id.fromMe.

Here is the JavaScript code snippet:

         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 */
         });

And here is a snippet of the JSON data logged in the console (personal info removed):

  "id": {
   "server": "c.us",
   "user": "phonenumber",
   "_serialized": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afdfc7c0c1cac1dac2cdcaddefcc81dadc">[email protected]</a>"
  },
  "name": "Name",
  "isGroup": false,
  "isReadOnly": false,
  "unreadCount": 0,
  "timestamp": 1596167676,
  "archived": false,
  "lastMsg": [
   {
    "id": {
     "fromMe": false,
     "remote": {
      "server": "c.us",
      "user": "phonenumber",
      "_serialized": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d0d151213181308101f180f3d1e53080e">[email protected]</a>"
     },

Answer №1

It is likely that this method will be effective, given that the lastMsg property is an array. It is important to ensure that lastMsg exists and that the accessed properties are accessible.

Another suggestion is to explore the lodash get function, as it can be quite handy for accessing nested properties.

let chats_active = [{ "id": { "server": "c.us", "user": "phonenumber", "_serialized": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c6c747372797269717e796e5c7f32696f">[email protected]</a>" }, "name": "Name", "isGroup": false, "isReadOnly": false, "unreadCount": 0, "timestamp": 1596167676, "archived": false, "lastMsg": [ { "id": { "fromMe": false, "remote": { "server": "c.us", "user": "phonenumber", "_serialized": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3b3abacada6adb6aea1a6b183a0edb6b0">[email protected]</a>" } } }] }];

var variable1 = 1596167676;
var variable2 = 1596167676;

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

Answer №2

The lastMsg is actually stored as an array and you need to access it through an index.

It is assumed that this array has only one object as an element.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What would be the most optimal choice for sorting in this particular situation within my PHP script?

I have successfully written a PHP script that can extract specific movie titles and ratings from a large file. However, I now need to modify the script to sort the movie titles with 'XXX' at the bottom of the list. I've considered using usor ...

Improve code efficiency by streamlining a function and using more effective syntax techniques

I've been learning how to condense code with jQuery. Can this script be written in a more concise manner without everything being on one long line? items.push('<li id="' + key + '">' + ' (key: ' + key + ')&apo ...

What are the circumstances under which JavaScript GCP libraries return null values?

My current project involves working with GCP and Firebase using typescript. I have been utilizing the provided libraries, specifically version 8 of Firebase, and have encountered some unexpected behavior. For instance (firebase, ver. 8.10.1) import 'f ...

Arranging a roster of models in C#

After developing a basic webapi2 program that returns JSON data, I encountered an issue with the order of child elements under their respective parents. Specifically, I need to rearrange the JSON structure so that certain MenuIds are placed under their cor ...

The initial number is inserted within the text box upon entering the final number

Whenever I enter the final digit, the text-box swallows up the initial number (it vanishes), resulting in an additional space. https://i.stack.imgur.com/Vfm8s.png https://i.stack.imgur.com/od4bQ.png Upon clicking outside of the text-box, the formatting ...

What is the best way to implement a Navbar link in React.js?

I am currently working on developing a website using Reactjs. I have successfully created a Navbar with two links - Home and Contact. However, when I click on the Contact link, although the URL changes accordingly, the page itself does not update. I have s ...

Extract data from arrays within other arrays

I have an array called societies: List<Society> societies = new ArrayList<>(); This array contains the following information: [{"society_id":1,"name":"TestName1","email":"Test@email1","description":"TestDes‌​1"}, {"society_id":2,"name":" ...

Is there a way to insert a dot after every two digits in a text field using Javascript upon keypress?

When inputting a 4-digit number (e.g. 1234) in my text field with value format 00.00, I want it to automatically adjust to the 12.34 format. How can I achieve this behavior using JavaScript on keyup event? ...

Node.js server allows for accessing AJAX requests seamlessly

I need to send a parsed AST of JavaScript code to a server for processing, and then receive a list of completions back. However, when I log the AST to the client console before sending it, the structure appears like this: [ { "id":0, "type":"Program", "ch ...

Updating the input value of one field by typing into another field is not functioning properly when trying to do so for

I'm managing a website with a form that has three fields which can be duplicated on click. Here is an excerpt of my code: $(document).ready(function() { var max_fields = 10; var wrapper = $(".container1"); var add_button = $("#niy"); var ...

The v-model in the Vue data() object input is not functioning properly and requires a page refresh to work correctly

Explaining this situation is quite challenging, so I created a video to demonstrate what's happening: https://www.youtube.com/watch?v=md0FWeRhVkE To break it down: A new account can be created by a user. Upon creation, the user is automatically log ...

Tips for resolving the issue of invalid functions as a child component in React

When I call a function that returns HTML code, everything works fine until I try to pass a parameter in. At that point, I receive an error saying "Functions are not valid as a React child." The issue is that I need to access the props from this function. T ...

The Facebook SDK fails to activate in Internet Explorer

I am currently working on implementing a Facebook login using the JavaScript SDK. Everything is functioning correctly in most browsers, but I am experiencing issues with certain versions of Internet Explorer. The login functionality is not working on my l ...

The jquery datepicker is malfunctioning after switching to another component

My current setup includes the following versions: jQuery: 3.3.1 jQuery UI: 1.12.1 AngularJS: 6 Here's a snippet of my code: <input id="test" type="text" class="form-control" value=""> In my component (component.t ...

The debate between client-side and server-side video encoding

My knowledge on this topic is quite limited and my Google search didn't provide any clear answers. While reading through this article, the author mentions: In most video workflows, there is usually a transcoding server or serverless cloud function ...

What steps should I take to improve the performance of this MySQL query in order to increase the number of concurrent calls

When we execute the query below to retrieve data from the DB1.Data table, it takes longer to complete. The output of this query represents concurrent calls derived from CDR information. Mysql query select sql_calc_found_rows H,M,S,(TCNT+ADCNT) as CNT fro ...

When the button is clicked, the JavaScript function is not being executed

I'm having a strange issue with my second button not working as expected. Despite appearing to be straightforward, the "Reset" button does not seem to be triggering the clear() function. Within the HTML code, I have two buttons set up to interact wit ...

Guide on utilizing angularjs $q.all() method with a dynamically generated set of promises

I am currently facing an issue with using $q.all() to wait for multiple promises to be resolved. I have created an array of promises and passed it to the all() method, but it doesn't seem to be working as expected. The promises in the array are gener ...

Utilizing a Web Interface for Remote Monitoring of Windows Servers

I am in need of creating a webpage that will indicate whether a server is currently operational or not. These servers are all Windows based, with some running on 2008 and others on 2003. They are spread across different networks within various client locat ...

Guide to making a Java Servlet for a specific jQuery.ajax () request?

In one of my files named wfd.proxy.js, I have the following code snippet: if (!WFD) { var WFD = {}; }; if (!WFD.Proxy) { WFD.Proxy = {}; }; WFD.Proxy = { SERVICE_URL : "/delegate/WFD/WFService?", PDF_SERVICE_URL : "/delegate/pdf-exporter?", ...