Ways to make a personalized item within an array using javascript

JSON: (The array within this.schedulerForm.get("schedularList").value contains the following array:

    const result = [{
                     formula_id:1,
                     quantity1:10,
                     quantity2:20,
                     quantity3:40
                     }]

Conversion JSON: (The above JSON array contains 1 object with 3 quantity values. I need to separate the quantity values into individual objects with the same formula_id, along with month and year. The output should be as shown below.)

    const result = [{
                      formula_id:1,
                      year:this.year,
                      month: this.month,
                      quantity:10
                      },
                       {
                      formula_id:1,
                      year:this.year,
                      month: this.month,
                      quantity:20
                      },
                      {
                      formula_id:1,
                      year:this.year,
                      month: this.month,
                      quantity:40
                      }]

component.ts:

 month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];
  year = new Date().getFullYear();
  getDate(n){
    const date = new Date();
     return date.getMonth() + n;
  }
 save() {
    console.log(this.schedulerForm.get("schedularList").value)
 }

Answer №1

Check out this code snippet that could be useful for your problem:

const info = [{
  id:1,
  amount1:10,
  amount2:20,
  amount3:40
}];

const currentYear = new Date().getFullYear();
const currentMonth = 13;

const analyzeItem = object => property => ({
  id: object.id,
  currentYear, 
  currentMonth,
  amount: object[property]
});

const attributes = ["amount1", "amount2", "amount3"];

const outcome = info.reduce((accumulator, object) => [...accumulator, ...attributes.map(analyzeItem(object))], []);
console.log(outcome);

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

Modifying Parent Component Layout Using Vue.js

I am currently in the process of converting a UI element into a component for the purpose of reuse. This particular element consists of two buttons that toggle the visibility of two DOM elements within the parent app. The state of these buttons is stored i ...

Regular expressions are compatible with JavaScript, but unfortunately, they are not supported

After successfully implementing this regex in my JavaScript for webpage validation, I attempted to incorporate it into my PHP script as a backup. However, every string I passed through the regex failed, even correct names. In an effort to resolve the issu ...

"Converting jQuery Form into a Wizard feature with the ability to hide specific steps

I'm working on a form where I need to hide a fieldset when a specific event is triggered. Inside the first fieldset, there is a select tag and when a certain option is selected, the second fieldset should be hidden. <form id="form1"> <fi ...

"Angular File Upload Made Easy with Drag-and-Drop Functionality and Cleverly Positioned

Encountering an issue with Angular File upload in conjunction with relatively positioned elements. The drop target is set to 100% width and height, absolutely positioned. While dragging a file over any non-relatively positioned element, the overlay functio ...

Tips for connecting an input tag within a popover to a Vue Model

I've got an input nested inside a popover content as shown below: JSFiddle Link HTML code snippet: <div id="vue-app"> <div class="btn btn-primary" data-toggle="popover" data-placement="bottom" title="Hello World!" data-html="true" data ...

Showing a header 2 element just once using both *ngFor and *ngIf in Angular

I have an array of words with varying lengths. I am using ng-For to loop through the array and ng-if to display the words based on their lengths, but I am struggling to add titles to separate them. Expected Outcome: 2 letter words: to, am, as... 3 lette ...

Cookies are strangely absent from the ajax call to the web api - a puzzling issue indeed for Web Api users

Hello, here is the code I'm working with using Ajax: function GetCurrentUserId() { return $.ajax({ type: "GET", url: rootUrl + '/api/Common/CurrentDateAndUser', dataType: 'json', ...

What is the method for locating all anchor tags "In General" within the inner HTML of a div using XPath?

This query is related to a discussion on anchor tags in this thread. I am interested in identifying all anchor tags within a string. The scenario provided below is similar to the aforementioned issue, however, I aim to accomplish this using xpath and angu ...

Is there a way for me to determine which specific dependency is triggering a warning due to utilizing another dependency?

After analyzing my browser console, I found the following warnings: index.js:126 [WDS] Warnings while compiling. warnings @ index.js:126 (anonymous) @ socket.js:47 sock.onmessage @ SockJSClient.js:67 EventTarget.dispatchEvent @ sockjs.js:170 ...

How can I create spacing between squares in an HTML div element?

Currently, I am working on my project using Laravel 5. I retrieve some integer values from a database and use them to create square divs in HTML. Below is the current output of my work. https://i.stack.imgur.com/sy2ru.png You may notice that there is spa ...

Using JQuery to reveal a hidden child element within a parent element

I'm facing a challenge with displaying nested ul lists on my website. The parent ul is hidden with CSS, causing the child ul to also remain hidden even when I try to display it using jQuery. One approach I've attempted is adding a class to the f ...

JSON Serialization Results Include a Property for Counting

In my C# project, I'm facing an issue with serializing an array of objects into JSON. The type of array I'm dealing with is Object[], not Array<Object>. Currently, the serialization process is handled automatically by a JsonMediaTypeFormatt ...

Javascript code requires server to have default text field values

Based on the choice made by a user, a text field box will either remain concealed or revealed: $("#aForm").on("change", function() { if ($(this).val() == "a") $("#textField").hide(); else $("#textField").show(); }); The issue arises when the ...

Performing an Ajax request to the server and then sending the retrieved data back to Charts.js

After extensively researching ajax, php, and related topics, I'm facing a challenge. I want to take an array retrieved from my database and integrate it into a chart.js script. The data retrieval seems fine as per Firebug inspection, but the issue ari ...

Retrieving information from a JSON file and transferring it to a URL

Is there a way to send the JSON data to my URL and receive all of the JSON data on the URL instead of just the data from 'resolvedQuery'? $update_response = file_get_contents("php://input"); $update = json_decode($update_response, true); $resul ...

In JavaScript, merging objects will exclusively result in an identifier being returned

When working with mongoose, I have encountered an issue where combining data from multiple finds only displays the id instead of the entire object. Interestingly, when I use console.log() on the object directly, it shows all the contents. Below are snippe ...

Merging a VUE project and a .NET framework project to unleash their full potential

Currently, I am working on a project that involves using VUE for the client side and .net framework for the server side. However, these two components are hosted as separate projects, requiring me to open different ports during development. I am aware tha ...

Troubleshooting problems with dynamic elements and qTip

On my page, I have an UpdatePanel where new forms are added when clicked. These new elements contain images that need to utilize qTip. This is the current setup: $(document).ready(function () { $('.ttip').qtip({ conten ...

Guide on deleting objects based on their IDs when the IDs are stored in a separate array using JavaScript

I have two separate arrays. One array contains only integers as IDs (from a searchBox) and the other array contains objects, such as: categories = [1, 2, 5, 8]; items = [ { title: 'Hello', description: 'any description you want', cat ...

Encountering an unusual issue: Unable to access undefined properties (specifically 'get')

I'm struggling to get the order history screen to display the order history of a specific user. Every time I navigate to the path, I encounter the error mentioned in the title. I double-checked the path for accuracy and made sure there are no spelling ...