Learn the steps for generating an array of objects in AngularJS or JavaScript

I have an array named $scope.data2 and I am looking to create another array of arrays based on the data provided below:

 $scope.data2 = 
                [     
                    {"dt":"07 Jul 2015","avgdelay":"10","code_sent_time":"07 Jul 2015 12:30 PM","reply_received_time":"07 Jul 2015 12:40 PM","time_diff":10},
                    {"dt":"07 Jul 2015","avgdelay":"10","code_sent_time":"07 Jul 2015 02:10 AM","reply_received_time":"07 Jul 2015 02:30 AM","time_diff":20 },
                    {"dt":"07 Jul 2015","avgdelay":"10","code_sent_time":"07 Jul 2015 03:10 AM","reply_received_time":"07 Jul 2015 03:15 AM","time_diff":5 },
                    {"dt":"07 Jul 2015","avgdelay":"10","code_sent_time":"07 Jul 2015 04:45 AM","reply_received_time":"07 Jul 2015 05:00 AM","time_diff":15 },
                    ...
                ];

The resulting array structure I aim to achieve is:

$scope.resarray = [     
                    {"dt":"07 Jul 2015","avgdelay":"10","data" : 
                                            [
                                            {"code_sent_time":"07 Jul 2015 12:30 PM","reply_received_time":"07 Jul 2015 12:40 PM","time_diff":10},
                                            {"code_sent_time":"07 Jul 2015 02:10 AM","reply_received_time":"07 Jul 2015 02:30 AM","time_diff":20 },
                                            {"code_sent_time":"07 Jul 2015 03:10 AM","reply_received_time":"07 Jul 2015 03:15 AM","time_diff":5 },
                                            {"code_sent_time":"07 Jul 2015 04:45 AM","reply_received_time":"07 Jul 2015 05:00 AM","time_diff":15 }
                                            ] 
                    },
                    ...
                ];                      

I want to organize my data so that each date has an array containing all 4 details for that specific date. I have attempted various methods without success. Any assistance in solving this issue would be greatly appreciated.

Here is the snippet of the code I have worked on:

    $scope.genarr = function()
{
var data2length = $scope.data2.length;
var firstdate = $scope.data2[0].dt;
var sourcecheckdate = firstdate.split(' ');
$scope.resarray = {};
var dtcheckflag = false;
var insertrow = null;
var j = 0;
var k = 0;
var z = 1;
var data=[];
for (var i=0;i<data2length;i++)
{
    var targetcheckdate = $scope.data2[i].code_sent_time.split(' ');

    if (targetcheckdate[0] === sourcecheckdate[0] && targetcheckdate[1] === sourcecheckdate[1] && targetcheckdate[2] === sourcecheckdate[2])
    {
        firstdate = $scope.data2[i].dt;
        sourcecheckdate = firstdate.split(' ');
    }
    else
    {
        firstdate = $scope.data2[i].dt;
        sourcecheckdate = firstdate.split(' ');
    }

        if (insertrow != firstdate) 
        {
            k = 0;
            $scope.resarray[j] = {"dt":$scope.data2[i].dt,"avgdelay":$scope.data2[i].avgdelay,"data":[]};
            $scope.resarray[j].data[k]= {"code_sent_time":$scope.data2[i].code_sent_time , "reply_received_time" :$scope.data2[i].reply_received_time , "time_diff" : $scope.data2[i].time_diff};
            insertrow = firstdate;
            j+=1;
        } 
        else 
        {   
            $scope.resarray[j].data[k]=  {"code_sent_time":$scope.data2[i].code_sent_time , "reply_received_time" :$scope.data2[i].reply_received_time , "time_diff" : $scope.data2[i].time_diff};              
        }

        k +=1;
}
};

Answer №1

Make sure to review the following link: http://plnkr.co/edit/BOYqNcdpi8uGKRraDAw1?p=preview

Implementation in the Controller:

$scope.data = []; //Initializing a new formatted array for data          
for(var k = 0; k < $scope.data2.length; k++) {
  var arrayData = {}; //Creating a temporary object
    arrayData.dt = $scope.data2[k].dt;
    arrayData.avgdelay = $scope.data2[k].avgdelay;
    arrayData.data = [];
    for(var j = 0; j<4; j++,k++) {
      if (arrayData.dt == $scope.data2[k].dt) {
      var tempObj = {'code_sent_time': $scope.data2[k].code_sent_time,
        'reply_received_time':$scope.data2[k].reply_received_time,
        'time_diff':$scope.data2[k].time_diff
      };
      arrayData.data.push(tempObj);
      }
    }  

  $scope.data.push(arrayData);  
}   

Answer №2

the content field is currently a string, but it needs to be an array.

 {"dt":"21 Sep 2021","score":"45","content" : 
   {
     {"item1":"21 Sep 2021 11:15 AM"},
     {"item2":"21 Sep 2021 01:30 PM"},
     {"item3":"21 Sep 2021 03:45 PM"},
     {"item4":"21 Sep 2021 06:00 PM"}
   }
 },

should be

 {"dt":"21 Sep 2021","score":"45","content" : 
   [
     {"item1":"21 Sep 2021 11:15 AM"},
     {"item2":"21 Sep 2021 01:30 PM"},
     {"item3":"21 Sep 2021 03:45 PM"},
     {"item4":"21 Sep 2021 06:00 PM"}
   ] 
 },

{} signifies an object, [] signifies an array

Answer №3

let freshData = [];
let dateTracker = {};

angular.forEach(oldData,function(entry){
  let temporary = {};    
  if(dateTracker[entry.date]){
    dateTracker[entry.date].push(entry);
  } else {
    dateTracker[entry.date] = [];
    dateTracker[entry.date].push(entry);
  }
});

angular.forEach(dateTracker,function(value,key){
  let object = {
    "date": key,
    "averageDelay": value[0].averageDelay,
    "dataEntries": value
  };
  freshData.push(object);
});

My solution should resolve the issue. oldData should be replaced with freshData for the updated values.

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

Creating a Distinct Interior Array Separate from the Exterior

I'm currently working on a project that involves creating a 2D array. I want the interior elements of this array to be black while the exterior elements should be white. However, my 2D array doesn't seem to be forming correctly - it looks more li ...

Tips for verifying an alphanumeric email address

I need to create an email validation script that allows only alphanumeric characters. <script type = "text/javascript"> function checkField(email) { if (/[^0-9a-bA-B\s]/gi.test(email.value)) { alert ("Only alphanumeric characters and spaces are ...

In Typescript, object properties make assertions about other properties within the object

I have a specific object that I use to store data received from an API. This object is structured as follows: class Storage { isReady: boolean = false; content: object || null = null; } I have noticed that when isReady is false, content is null. Con ...

What is the best way to incorporate animation into Bootstrap dropdowns?

Is there a way to incorporate animation into the dropdown feature? I'm assuming it can be achieved by adjusting popperConfig, but how exactly? Currently, the dropdown-menu has an automatically generated inline style, for example: position: absolute; ...

fetch information using ajax and jquery

I'm facing an issue with my ajax request on my website. I'm trying to dynamically fetch pages from a database using jquery and ajax. However, I'm not getting any response, and I'm unsure whether the problem lies in my php code or my j ...

Data is successfully being stored in an array in AngularJS, however, it is not appearing in the user interface

Having an issue with displaying updated data on my UI. I am successfully pushing data into the database and an array using Angular 2-way binding. The data is being pushed as confirmed by the console, but it's not showing up on the user interface. Con ...

Combining numerous base64 decoded PDF files into a single PDF document with the help of ReactJS

I have a scenario where I receive multiple responses in the form of base64 encoded PDFs, which I need to decode and merge into one PDF file. Below is the code snippet for reference: var pdf_base1 = "data:application/pdf;base64,JVBERi0xLjQKJfbk/N8KMSAwIG9 ...

Issue with DropdownListFor validation using jQuery when the onchange event triggers submission

DropdownListFor @Html.DropDownListFor(x => x.selectedDateFilter, new SelectList(Model.bydatefilter, "id", "dt", Model.selectedDateFilter), "--Select Date--", new { onchange = @"this.f ...

"In strict mode, the object is subjected to specific rules

I am facing a challenge with an object in my project that needs to run the content of the page within strict mode. Even after attempting to return it for global scope usage, I still haven't been able to resolve the issue. (function($) { "use stric ...

Utilize Javascript/Jquery to categorize JSON data based on the days of the week (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)

A function is provided below that retrieves data for a chart. The output produced by this function is structured as follows: [Object { date=Date, value=112, volume=1469}, Object { date=Date, value=124, volume=539}, Object { date=Date, value=114, vo ...

What techniques can I implement to optimize the speed of this feature in JavaScript?

I have developed a feature that highlights any text within a <p> tag in red based on a user-specified keyword. The current implementation works well, but it is slow when dealing with over 1000 lines of <p>. Is there a faster way to achieve this ...

Supplying information to my ejs template while redirecting

I am currently working on a feature that involves sending data from the login page to the home page when the user is redirected. This data will then be used in the home EJS file. Below is the code snippet I have implemented: module.exports = functio ...

React encountered a 400 error when attempting to call a function in node.js

While attempting to call a registration endpoint from a React front-end to a Node.js back-end using Axios, I encountered a 400 error: http://localhost:9000/user/register 400 (Bad Request) Here is my code: /* React component for user registration */ impo ...

transforming json data into an array or map

Once my REST API responds, it provides the following JSON content: [{ "key": "apple", "value": "green" }, { "key": "banana", "value": "yellow" }] Managing the data, I use the following code to iterate through the list: this.props.json.ma ...

Lots of questions arise when dealing with a combination of a restful back-end and Angular.js

Alright, it's time to dive into building a web application using Jboss and restEasy for the backend, with Angular.js as the chosen MVC front-end framework. This is uncharted territory for me, so here come my myriad questions: Should I utilize securi ...

Unraveling the mysteries of deciphering extended JSON information

Issue with Data Interpretation I am facing a challenge in my project that is more related to understanding and interpreting data rather than writing code. The project involves using a NoSQL database, specifically MongoDB, to store information sampled from ...

Maximizing Server Performance with Query Data Caching

I am currently developing an Express app that involves transferring data from views to a database. However, the majority of the data needs to be linked to other data within different tables in the database. For instance, there is a "choose student name" d ...

Is there a way to retrieve the file path of the file that is imported using an alias in Vite (Vue3)?

Hello! I have a few inquiries. Is it feasible to obtain the file path of the file utilizing an alias for import in Vite (Vue3)? Setup Here's the directory structure I'm using, purely for illustrative purposes: src/ module_a/ some_ ...

"jQuery's .each() method is only iterating through the last element in

I am encountering an issue with this function not operating correctly... only the last Element shows the box. NOTES: <aside> is set to position: fixed; and I understand that this is not the "correct" use of <article> tags, but it helps me dist ...

Troubleshooting: Vue Component Unable to Locate Property

Just dipping my toes into Vue with a simple test implementation and running into some trouble breaking down data into components. Let's take a closer look at the code: <body> <header id="main-header"> <custom-header></ ...