Angular array mapping techniques

My JSON Object

$scope.selectedItems ={
    "RECORDS": [
        {
            "Id": 23040035705987,
            "arriveddate": "2015/04/24",
            "expirationDate": null,
            "replacedDate": null,
            "processDate": "2015/04/24"
        },
        {
            "Id": 23070041800654,
            "arriveddate": "2015/04/24",
            "expirationDate": null,
            "replacedDate": null,
            "processDate": "2015/04/27"
        },
        {
            "Id": 23040035705984,
            "arriveddate": "2015/04/24",
            "expirationDate": null,
            "replacedDate": null,
            "processDate": "2015/04/24"
        },
        {
            "Id": 23040035705983,
            "arriveddate": "2015/04/24",
            "expirationDate": null,
            "replacedDate": null,
            "processDate": "2015/04/24"
        }
    ]
}

what i am striving for

My goal is to separate the IDs corresponding to unique processing dates into a new object. For example, the processing date 24/04/2015 matches with the IDs ending with 83, 84, 87, and the processing date 27/04/2015 matches with the ID ending with 54.

My desired JSON object

{
    "processDate": [
        "2015/04/24",
        "2015/04/27"
    ],
    "Id": [
        [
            23040035705983,
            23040035705984,
            23040035705987
        ],
        [
            23070041800654
        ]
    ]
}

my approach

angular.forEach($scope.selectedItems.RECORDS, function ( item ) { 
                $scope.ProcessDate = item.processDate;
                if($scope.processDatesSelected.indexOf($scope.ProcessDate) == -1){
                  $scope.processDatesSelected.push($scope.ProcessDate);
                }

                if($scope.processDatesSelected.indexOf($scope.ProcessDate) != -1 && $scope.id.indexOf(item.Id) == -1 ){
                    $scope.id.push(item.Id);
                }

            });

  $scope.changesSelected.push({processDate:$scope.processDatesSelected,Ids:$scope.id});
  console.log(JSON.stringify($scope.changesSelected));

Issue arises with the ID mappings, I have created a Plunker for reference (http://plnkr.co/edit/mkLXdOKayaqyDDDheFeu?p=preview) Any assistance would be greatly appreciated.

Answer №1

Here is a new approach for you to try: http://example.com/code

When iterating through the selected items in Angular, ensure you capture the processDate and assign it to $scope.ProcessDate. Then, check if the processDate is already in the processDatesSelected array. If not, add it to the array and initialize an empty array at the corresponding index in the id array. If the processDate is already in processDatesSelected, check if the item's Id is already in the corresponding id array. If not, push the Id to the id array at that index.

Answer №2

To create an array for each date, you need to consider the date when creating the array for the "id" values.

Here is an example to help you understand: http://plnkr.co/edit/vrig4P9SgZh8Kk7BkyEt?p=preview

First, you should find the index of the item from the initial array, then insert the element at the correct position.

var processDateIndex = $scope.processDatesSelected.indexOf($scope.ProcessDate);
if(processDateIndex != -1 && $scope.id.indexOf(item.Id) == -1 ){
  if ($scope.id.length < processDateIndex+1)
  {
    $scope.id.push([]);
  }
    $scope.id[processDateIndex].push(item.Id);
}

You can also consider using a structure like the following for better organization and maintenance of the collection:

{
    "processDate": [
        { 
            Date: "2015/04/24",
            Ids: [
                23040035705983,
                23040035705984,
                23040035705987
            ]
        },
        {
            Date: "2015/04/27",
            Ids: [
                23070041800654
            ]
        }
    ]
}

Answer №3

Here's a solution that should work:

let output = {
    processDates: [],
    Ids: []
};

for(let i = 0; i < $scope.pickedItems.SETS.length; i++) {
    let item = $scope.pickedItems.SETS[i],
        index = output.processDates.indexOf(item.processDate);
        
    if(index === -1) {
        output.processDates.push(item.processDate);
        output.Ids.push([item.Id]);
    } else {
        output.Ids[index].push(item.Id);
    }
}

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

Is it possible to receive live updates from a MySQL database on a webpage using node.js and socket.io?

I've been following a tutorial that teaches how to receive real-time updates from a MySQL database using Node.js and Socket.io. Check it out here: Everything seems to work fine on the webpage. I can see updates in real-time when I open the page on tw ...

Issue encountered while attempting to create entity in jhipster

After executing the creation of an entity in the command line, JHipster successfully generated Java and script files but encountered issues with updating the database. No new table was inserted despite starting MySQL and turning off the application befor ...

When a row is clicked, retrieve the data specific to that row

I have implemented a data-grid using react-table where I pass necessary props to a separate component for rendering the grid. My issue is that when I click on a particular row, I am unable to retrieve the information related to that row using getTrProps. ...

I'm having trouble receiving a response after uploading an image on Cloudinary using React js

Once the image is uploaded using the API, it should return a response. However, I am not receiving any response through the API even after uploading the image. if (pic.type === "image/jpeg" || pic.type === "image/png") { const da ...

How does the behavior of instanceof change when used within JSON.stringify()?

I am utilizing the decimal.js library for conducting financial calculations within Node. In my code, I have crafted a custom JSON.stringify replacer function. However, I have noticed a discrepancy in the results of property type tests conducted using insta ...

The array used within the useEffect hook and the getCoordinates function appears to be distinct when printed with console

Utilizing GoogleMap API for Custom Location Display I have an imported array of JSON objects named data which includes an address property. The Google Maps API is used to retrieve coordinates from the addresses in order to generate custom markers displaye ...

Tips for Removing Padding in Material UI Container Component

I'm currently working on creating a hero banner using the material-ui framework and I've encountered an issue. Here's what I have so far: https://i.stack.imgur.com/UXTDY.png However, I'm facing an irritating problem with left and rig ...

Retrieving FormData using ajax and passing it to aspx.cs code

After adding a debugger in the console, I am receiving confirmation that the file has been uploaded successfully. However, the debugger is not reaching the code behind, or in other words, the code behind is not accessible. This is the JavaScript file: fun ...

ng-view is the culprit behind the website's fatal error

Encountering a "RangeError: Maximum call stack size exceeded" in the console while trying to recreate a basic routing example from w3schools. The crash seems to be linked to <div ng-view></div> in index.html. Despite making minimal changes from ...

Using JavaScript to create a tree structure with hierarchical organization in JSON

Having some trouble converting a nested hierarchical tree from a JSON array. Looking to create a hierarchical tree structure from the provided JSON data. Below is the data: [{ "_id" : "59b65ee33af7a11a3e3486c2", "C_TITLE" : "Sweet and Snacks", ...

Getting the chosen value from a dropdown menu on form submission using PHP

How to Populate a Combo Box from a Database in PHP? <td>Item Name:</td> <td><select name="items"> <option value="0" selected="selected"> Choose</option> <?php while($row = mysql_fetch_ass ...

Preventing users from inputting the symbols "+" or "-" in a React JS input field

Essentially, the input field should only accept values between 1 and 999 Input Field : <input type="number" value={value} onChange={this.props.onViltMaxUserChange} min="0" max="999" /> onChange : onViltMaxUserChange = _.throttle(e = ...

Apply a class to each consecutive element following the current one until reaching a child element with a

My goal is to apply a "bg-info" class using jQuery to all rows (tr) that come after odd rows with a child element of "test". The "bg-info" class should be removed when a row with a child element of "test" is encountered, and then re-applied when the next o ...

AngularJS Directives Directory: A hub for all things related to

Can you recommend any websites or resources where I can find angularjs directives that have been created by the community? Just to clarify, I'm not looking for the ones that come built-in with angularjs. ...

What could be the reason for this function failing to calculate the mean of a set of data points?

I'm facing a challenge with this beginner problem. "A task for you: Calculate the average score of a class whose test scores have been graded by a teacher. Your mission is to complete the getAverage function, which receives an array of test sco ...

Obtain the selected node in FancyTree

When a button is clicked, I need to grab the current node that is in focus. In my attempt to achieve this, I utilized the getFocusNode() method within a click event handler like so: function retrieveFocusedNode() { var currentNode = $("#tree").fancy ...

Invoke OnSelectedIndexChanged from GridView prior to any other function execution

In my scenario, there are two GridViews available. The first GridView allows the user to select a row, based on which a corresponding list will be displayed according to the selected GridView ID. First Grid: https://i.stack.imgur.com/d0OKq.png Second Gri ...

Mastering the onKeyPress event for Material UI text fields: A step-by-step guide

I have a TextField component from Material UI as shown below: <TextField id="todo-textarea" label="Enter new todo" placeholder="ToDo" onChange={this.props.toDoOnChange} onKeyPress={(ev) => { ...

Utilizing a custom function declared within the component to handle changes in Angular's ngOnChanges

Although it may seem like a simple question, I'm struggling to find a solution. Here's the issue at hand: In my Angular Component, there's a function that I need help with. export class RolesListComponent implements OnInit, OnChanges { ...

AngularJS allows users to seamlessly retain any entered form data when redirected, enabling users to pick up right where they left off when returning to the form

I am currently working on a user data collection project that involves filling out multiple forms. Each form has its own dedicated HTML page for personal details, educational details, and more. After entering personal details and clicking next, the data ...