Retrieve the most recent timestamp from the JSON data returned

I need assistance in extracting the latest timeStamp and userID from the JSON response where actualDataArray.status is "Approved" to populate it on the template.

{
  "dataArray": [
    {
      "Id": 11,
      "Name": "HJ Enterprises",
      "Code": "HJC",
      "description": "HJ APProved",
      "Status": "OK",
      "actualDataArray": [
        {
          "timeStamp": "2019-05-07-06.26.23.991068",
          "status": "Approved",
          "userID": "@23444",
          "articles": ""
        },
        {
          "timeStamp": "2019-05-07-06.37.27.978668",
          "status": "Rejected",
          "userID": "@1234",
          "articles": "articles"
        },
        {
          "timeStamp": "2019-05-08-06.26.28.991068",
          "status": "Approved",
          "userID": "@1233e",
          "articles": ""
        },
      ],


    },

The desired output should be the most recent timeStamp and corresponding userId for that timestamp. Can you please help me with this?

Answer №1

Retrieve the most recent object with an Approved status using this method.

const data = {
  "dataArray": [
    {
      "Id": 11,
      "Name": "HJ Enterprises",
      "Code": "HJC",
      "description": "HJ APProved",
      "Status": "OK",
      "actualDataArray": [
        {
          "timeStamp": "2019-05-07-06.26.23.991068",
          "status": "Approved",
          "userID": "@23444",
          "articles": ""
        },
        {
          "timeStamp": "2019-05-07-06.37.27.978668",
          "status": "Rejected",
          "userID": "@1234",
          "articles": "articles"
        },
        {
          "timeStamp": "2019-05-08-06.26.28.991068",
          "status": "Approved",
          "userID": "@1233e",
          "articles": ""
        },
      ],


    }
  ]
}

let dataArr = data.dataArray
dataArr.forEach((dataPoint, i) => {
  let actualDataArray = dataPoint.actualDataArray
  let sortedActualDataArray = actualDataArray.sort((a, b) => {
    (new Date(a.timeStamp) > new Date(b.timeStamp)) ? 1 : -1
  })
  
  let timeStampElem = undefined
  
  if(dataPoint.status != "Ok"){
    timeStampElem = tempSearchArr[0]
  }
  else {
    timeStampElem = tempSearchArr[1]
  }
  console.log(timeStampElem)
  console.log(`TimeStamp: ${timeStampElem.timeStamp}`)
  console.log(`UserID: ${timeStampElem.userID}`)
})

Answer №2

Give this code a shot:

let dataObj = {
    "dataArray": [
        {
            "Id": 11,
            "Name": "HJ Enterprises",
            "Code": "HJC",
            "description": "HJ Approved",
            "Status": "OK",
            "actualDataArray": [
                {
                    "timeStamp": "2019-05-07-06.26.23.991068",
                    "status": "Approved",
                    "userID": "@23444",
                    "articles": ""
                },
                {
                    "timeStamp": "2019-05-07-06.37.27.978668",
                    "status": "Rejected",
                    "userID": "@1234",
                    "articles": "articles"
                },
                {
                    "timeStamp": "2019-05-08-06.26.28.991068",
                    "status": "Approved",
                    "userID": "@1233e",
                    "articles": ""
                }
            ]
        }
    ]
};
let approvedUsers = {};
let totalData = dataObj.dataArray.length;
let i = 0;
while(i < totalData) {
    let actualsData = dataObj.dataArray[i].actualDataArray;
    let actualLength = actualsData.length;
    let j = 0;
    while(j < actualLength) {
        if (actualsData[j].status === "Approved") {
            approvedUsers[actualsData[j].userID] = actualsData[j];
        }
        j += 1;
    }    
    i += 1;
}
console.log(approvedUsers);

In this instance, I am collecting all the data with the status "Approved" into a separate variable and display it using console.log(). You are free to utilize this variable as needed.

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

Guide on making a PDF input field function like a regular input field with PDF.js

Whenever I encounter input fields in a pdf file, I attempt to use pdf js to interact with them. However, I have been facing challenges in doing so. Allow me to provide an example of my objective: const canvas = document.getElementById(`canvas-${this.page ...

Setting the current date of a jQuery datepicker to the value of an input tag

I am looking to assign a value to an input tag that has a datepicker attached to it. Upon initialization of the datepicker, I want to set this value. Below is a hypothetical example of what I am trying to achieve: HTML: <input id="test" value="">&l ...

The ongoing ESLint conundrum: Balancing between "Unused variable" and "Unknown type" errors when utilizing imports for type annotations

I've encountered a linting issue and I need some guidance on how to resolve it. Here's the scenario - when running $ yarn lint -v yarn run v1.22.4 $ eslint . -v v6.8.0 With plugins vue and @typescript-eslint, I have the following code in a .ts ...

Save the ID values for dialogs that are created dynamically in the store

Encountering an issue with storing values in dynamically created buttons that can open a dialog box. The dialog is the same for all buttons, so the definition looks like this: $('<div id="dialog-form" title="Change coordinates">' + ...

Guide to automatically filling in a form's fields with information from a database by clicking on a link

Currently, I have a form in HTML that is designed to gather user/member information. This form connects to a database with multiple columns, with two key ones being "user_email" and "invoice_id". Upon the page loading, the input for "user_email" remains hi ...

Are there any alternative OpenAPI schemas that can produce more favorable Flow/TypeScript types, as the `oneOf` keyword is currently generating undesirable types?

We possess an OpenAPI schema that looks like this: { "openapi": "3.0.1", "paths": { "/v1/tool/breadcrumbs/{hierarchyId}/{categoryId}": { "get": { "tags": [ "V1-tool" ], ...

Guide on dynamically assigning the value of an Angular variable to another variable

My website has a slideshow feature with left and right buttons, similar to this example: . I am using Angular to change the image when the left or right button is clicked. In the function, I am incrementing a value: /*SlideShow Pictures*/ $scope.pic ...

Prop type failure: The `actions` prop is specified as mandatory in the `Testing` component, however, its value is currently undefined

I am working on a project that involves creating a login form using React and Redux. Here's a snippet of my app.js: import React from 'react'; import { render } from 'react-dom'; import Input from 'react-toolbox/lib/input&apo ...

Troubleshooting TS2769 Issue with Protect Middleware in Express.js

When trying to secure routes on an Express server, I attempted to simplify my middleware, but I continue to encounter an error: src/routes/userRoutes.ts:10:19 - error TS2769: No overload matches this call. The last overload gave the following error. Argum ...

What are some of the most effective methods for transferring data from a database using curl?

I've been diving into php CURL lately, but I'm having trouble understanding how it sends data. It seems like sending a php array or object directly from a database using curl isn't feasible, but using JSON as a medium for the data is possibl ...

Efficiently Populating Arrays Without Blocking

Let's dive into the scenario... Here is the template for our component <template> <div> <loader v-show="loading"></loader> // display loading animation <div v-show="!loading"> <div v-for="group in groups ...

What steps can I take to troubleshoot a non-functional button in a Bootstrap 5 Modal?

I have a Django based web site that utilizes Bootstrap 5 for styling. Among the data presented on the site is a table with a notes column containing lengthy text. To enhance readability and keep the table compact, I attempted to integrate the Bootstrap Mod ...

Inconsistencies observed in the functionality of window.location.reload(true)

I have been developing a feature for my website that automatically logs users out after a certain period of time. Within this functionality, I have incorporated the window.location.reload(true) method in three different sections of my code. Two of these in ...

Tips for implementing *ngFor directive in an Angular child component to generate a table

My goal is to showcase a table of users by incorporating the <tr> tag within a loop using (*ngFor). In UserComponent.html: <div class="theme-2"> <div class="example-container mat-elevation-z8"> <app-user *ngFor="let user of use ...

Ways to resolve the Face4 to Face3 issue

After stumbling across some old code, I discovered that it was mostly functional. var geom = new THREE.Geometry(); geom.vertices = testRect.verts(); for ( var i = 0; i < verts.length; i+=4 ) { geom.faceVertexUvs[0].push([ new THREE.Vector2 ...

The foundation grid system is experiencing difficulties when implemented on an Angular form

After successfully installing Foundation 6 on my Angular project, I am facing an issue with the grid system not working properly. Despite numerous attempts to troubleshoot and debug, I have not been able to resolve this issue. If anyone has any insights or ...

The jQuery Tab functions are incompatible with certain versions of jQuery-UI

After finding inspiration from a certain link, I successfully included a custom range slider on my website. If you're curious, you can check out the details here. To make it all work smoothly, I experimented with two different versions of jquery-ui: ...

Loading data onto a page using jQuery in ASP.NET after a postback

Currently experimenting with a jQuery plugin called jQuery Autocomplete Tokenizer. I'm facing an issue where I need to reload the values back into the textbox after the page is posted back, retaining whatever items were previously entered. Here' ...

What is the process for testing ng-select in Angular using the testing library?

Below is a list of companies displayed in an ng-select: <div class="input-group"> <ng-select role="company" id="company" class="form-control" #Company formControlName="company"&g ...

I want to know the most effective way to showcase particular information on a separate page using Angular

Recently, I've been working with a mock json file that contains a list of products to be displayed on a Product page. My goal is to select a specific product, such as 'Product 1', and have only that product's information displayed on th ...