Attempting to categorize JSON object elements into separate arrays dynamically depending on their values

Here's the JSON data I'm currently working with:

?$where=camis%20=%2230112340%22

I plan to dynamically generate queries using different datasets, so the information will vary.

My main objective is to categorize elements within this array into distinct arrays based on inspection dates.

For each unique inspection date, I aim to group those specific inspections into their own collections.

  1. If I had advance knowledge of the dates, I could easily iterate through the elements and organize them into separate arrays.
  2. Is there a way to create these arrays dynamically?

The ultimate goal is to present each set of inspections (grouped by inspection date) on a webpage using Angular 5. The website is functioning correctly, and all requests are being processed as intended.

Eventually, I hope to achieve a layout similar to this, utilizing the dates received in the response:

2016-10-03T00:00:00

List of inspections

2016-04-30T00:00:00

List of inspections

2016-04-12T00:00:00

List of inspections

Just for reference, here's the snippet of code that I'm currently implementing:

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.title = +params['camis']; // (+) converts string 'id' to a number
      this.q.getInpectionsPerCamis(this.title).subscribe((res) => {
        this.inspectionList = res;
          console.log(res);
      });
      // In a real app: dispatch action to load the details here.

    });

  }

I wish I could provide more details at this stage, but my primary focus is getting started on this task.

Answer №1

I opted for jQuery to speed up my coding process, although the conversion to Angular shouldn't be too challenging (I just didn't feel like dealing with an Angular app at the moment)

If you have any inquiries, please don't hesitate to ask.

$(function() {
  let byDateObj = {};
  $.ajax({
    url: 'https://data.cityofnewyork.us/resource/xx67-kt59.json?$where=camis%20=%2230112340%22'
  }).then(function(data) {
    //possibly check if the data is an array, but skipping for now
    byDateObj = data.reduce(function(cum, cur) {
      if (!cum.hasOwnProperty(cur.inspection_date)) cum[cur.inspection_date] = [];
      cum[cur.inspection_date].push(cur);
      
      return cum;
    }, byDateObj);
    
    console.log(byDateObj);
  }, console.error);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

The Value of Kendo Data

Below is my current kendo code snippet: <script> $("#dropdowntest").kendoDropDownList({ optionLabel: "Select N#", dataTextField: "NNumber", dataValueField: "AircraftID", index: 0, ...

Send the Children prop to the React Memo component

Currently, I am in the stage of enhancing a set of React SFC components by utilizing React.memo. The majority of these components have children and the project incorporates TypeScript. I had a notion that memo components do not support children when I en ...

Can an ImageView be transmitted to another Activity using GSON?

Is there a method to transfer an entire ImageView to another activity? Can GSON be utilized for this purpose? ...

What is causing the component to render three times?

Below is the structure of my component: import { useEffect, useState } from "react"; function Counter() { const [count, setCount] = useState(0); console.log("comp run"); const tick = () => { setCount(count + 1); conso ...

Tips on incorporating "get_template_directory_uri" into a JavaScript function

I am currently working on my WordPress PHP file code, where I have included a JavaScript snippet to display names and images from a query. While the names are being displayed correctly, I am encountering an issue with the images not showing up. After tryi ...

Creating a prompt within a while loop

Issue with the code is that it should only progress if the user inputs "rock", "paper" or "scissors". However, after re-entering any input the second time, it still moves on despite passing the condition in the while loop. For instance, entering "asdf" p ...

Issues connecting to servicenow have been detected

I encountered an error while attempting to connect to ServiceNow using JSON. Here is the code I am trying to execute: from servicenow import ServiceNow from servicenow import Connection conn = Connection.Auth(username='admin.main', password=&ap ...

Launching npm start does not automatically open a browser tab

I'm currently learning angularjs 2 and I'm eager to create my first application using the framework. Following the guidelines on their official website, I proceeded with all the steps outlined in this link. In step 6, I am required to run the com ...

Ways to duplicate an array in the C++ programming language

Attempting to capture array instances in a function named doSomething poses a challenge, as Arrays in C++ are passed by reference, making it impossible to achieve the desired outcome. Is there a workaround available to resolve this issue? #include <ios ...

How can we address the tagging directive problem of binding tags as an array of JSON objects and ensuring that tagging functions properly with the ng-keypress event?

Check out this plnkr example. I'm having trouble binding my tags list with ng-model. I want to bind the tags as an array of objects on a function call using ng-keypress, and then post it to a json file in a specific format. Here is what I am looking f ...

Having difficulty with installing the ttf-loader for React with Typescript

Currently, I am working on a project using React with TypeScript and trying to incorporate the font feature in react-pdf/renderer. The font has been successfully imported and registered as shown below: import { Text, View, StyleSheet, Font } from "@re ...

Ways to extract data from a JSON object

When using my web application, the Web API responds with the following JSON object: [ { "templateID":1, "template":"{\r\n \"Body\": \"sample date hete hee. Name\"\r\n}" }, { "templateI ...

Issue encountered when executing the migration fresh seed: SyntaxError, which indicates the absence of a closing parenthesis after the

Having trouble with a nextJS project that utilizes mikro-orm? Struggling to overcome this persistent error for days: C:\Users\BossTrails\Documents\core.nest-main_2\node_modules\.bin\mikro-orm:2 basedir=$(dirname "$(e ...

Can JavaScript's Gamepad API be used to register a custom game controller?

Background Story Working on a virtual reality app with A-frame to showcase VR gadgets. Custom controllers connect via websocket/bluetooth and we want them compatible with tracked-controls. These components use Gamepad API for model positioning and are fri ...

Display elements on hover of thumbnails using CSS

I'm struggling with the logic of displaying images when hovering over corresponding thumbnails using only CSS. If necessary, I can do it in JavaScript. Here's my latest attempt. <div id='img-container' class='grd12'> ...

Implementing conditional button visibility in Angular based on user authorization levels

I've been experimenting with the following code snippet: <button ng-if="!isAuthenticated()" ng-click="deleteReview()">Delete</button> In my JavaScript, I have: $scope.isAuthenticated = function() { $http.get("api/user ...

Filtering Arrays of Objects: A Guide to Filtering in JavaScript

Could really use some assistance with sorting an array of objects in javascript. My users array looks like this: var users = [ { first: 'Jon', last: 'Snow', email: '<a href="/cdn-cgi/l/email-protection" class="__ ...

Tips for breaking apart elements of a JavaScript array when a specific delimiter is present in an object property

I am facing a challenge with an array of objects where some properties contain commas. My goal is to split these properties into new objects and recursively copy the rest of the properties into new array elements. For example, consider this original array ...

Exclude JSON entries that have null child elements

Here is the JSON data I have: { "id": 81, "bank_id": 2, "service_id": 1, "created_at": "2014-12-05 06:40:23", "updated_at": "2014-12-05 06:40:23", "alias": "remit", "alias_burmese": "remit", "reputation": null, "contact": null, "service": null }, { "id": ...

Tips for combining enable and disable properties in flatpickr.js?

I'm facing a challenge with using both the enable and disable properties in flatpickr.js. The enable property returns a range of dates that should be enabled, but I specifically want to disable certain days within that range, like weekends. datePicker ...