What is the process for generating an array of objects using JavaScript?

I am struggling to create an array of objects using JavaScript and facing errors with new lines added where I need to split the messages and collect row numbers. The row numbers should be comma-separated if it is a repetitive error message.

I found a solution but it seems messy as it adds an "undefined" string when concatenating the rows numbers.

Furthermore, I require a solution optimized for handling large data as I can expect error messages ranging from 3000 to 7000. Also, I am working with Angular 6 version.

Here is my desired output:


{
    "No address details found for record at row ": "3,4",
    "Invalid Street Number at row ": "5",
    "Invalid Zip at row": "6,7,11"
}

Answer №1

To separate the key and value, you can utilize the regex /\s*(.*?)(\d+).$/. Utilize the exec function to iterate through the matches and update the output object accordingly. If the key is already present, it will be updated. Otherwise, a new key will be added to the object.

var errorMessage = `No address details found for record at row 3.
                No address details found for record at row 4.
                Invalid Street Number at row 5.
                Invalid Zip at row 6.
                Invalid Zip at row 7.
                Invalid Zip at row 11.`

let regex = /\s*(.*?)(\d+).$/gm,
    output = {},
    match;

while(match = regex.exec(errorMessage)) {
  const [,key, value] = match;
  if(output[key])
    output[key] += `,${value}`
  else
    output[key] = value
}

console.log(output)

Answer №2

In this adjusted regular expression, the period has been removed:

var errorDisp = errorMsg.split(/^(.*)(\d+)\./gm);

After that, ensure you verify that a is false before appending it to the comma-separated list:

if (a) object[aa[i - 1]] += "," + a;

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

What ways can we implement identification features in Flutter Web applications, such as adding an ID or name property?

While developing a Flutter Web application, I am exploring a Web-UI-Testing framework that is Selenium-based. Unfortunately, I am struggling to locate an HTML element that represents a specific flutter widget by its id or name attribute. The widget key doe ...

The tooltip popup does not appear within the nz-tabs

Looking to enhance my two tabs with an info icon preceding the tab text, along with a tooltip popup that appears when hovering over the icon. Despite trying different methods, I have yet to achieve the desired outcome. <nz-tabset [nzLinkRouter]=&qu ...

The regular expression should consist of just letters and a single dot

Currently, I am working on creating a regular expression that allows only letters and one dot. However, there is a specific rule to follow: the dot cannot be located at the beginning or end of the string. For example: abc.difference This is what I attem ...

Can different classes be assigned as "dragenter" targets?

Is it possible to apply the Jquery "dragenter" event to multiple targets or classes simultaneously? I tried this approach, but it doesn't seem to be working: $('.list').on('dragenter','.class1, .class2', function(e) { ...

Discovering the required rotation angle for an object to directly face another using JS HTML5 CANVAS

Hey there, I'm currently working on a game project in Javascript where I have a player and a cursor. I already know the positions of both objects, but what I need help with is determining the angle in degrees or radians that the player needs to rotate ...

It appears that the font in style.css is not being updated properly and seems to resemble

My issue lies within my CSS code. The text on my website is not displaying correctly and seems to be ignoring the styling that I have applied. Even though I have used similar styling on other buttons which look fine, this specific text element is causing p ...

The browser has surpassed the maximum call stack size while trying to refresh with socket.io, causing an error

I've encountered an issue with my Node js server crashing whenever I refresh the browser. The websocket connection works fine initially, but upon refreshing, the server crashes with the following error: E:\Back\node_modules\socket.io-pa ...

Guide to implementing ES2022 modules within an extension

After making changes in my extension code to test various module types, I decided to modify my tsconfig.json file as follows: { "compilerOptions": { "declaration": true, "module": "ES2022", ...

Building a table using jQuery and adding elements using JavaScript's append method

Greetings! I've been attempting to add new records from a form that registers or updates student information, but unfortunately it doesn't seem to be functioning correctly. Can anyone point me in the right direction as to why this may be happenin ...

Navigating to a particular page in ReactJS using a unique JSON identifier

I need to navigate to a particular page and display a specific JSON Object. If the JSON Object contains ID: 1, then it should redirect to localhost:300/users/1 and display the data of ID 1. I have also linked another JSON file that contains user addresses, ...

Having difficulties achieving successful API requests in Next.js and Snipcart

I'm currently diving into the world of Snipcart, and I'm encountering some issues connecting to your API. I'm using Next.js and haven't been able to find any solutions on the forum or in the documentation that address my specific proble ...

The values returned by the Node.js API can vary for identical requests

I am currently learning how to use Node.js + Express in order to create a REST API. Within this API, I have implemented the following method: apiRouter.route('/training/session/byId/:id_session') // ===== GET ======= .get(function(req, res ...

AngularJS: Error message stating that '$scope is undefined'

Encountering '$scope is not defined' console errors in this AngularJS controller code: angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Au ...

Creating a JSON representation of a join-model along with its related models

Within my Rails application (version 4.1.5 / ruby 2.0.0p481 / win64), I've established a many-to-many relationship between Student and Course. This association is represented by a join model called StudentCourse, which includes an additional attribute ...

Add a new element to the page with a smooth fade-in animation using jQuery

var content = "<div id='blah'>Hello stuff here</div>" $("#mycontent").append(content).fadeIn(999); Unfortunately, the desired effect is not achieved with this code. I am trying to create a sleek animation when adding new content. ...

Using typescript with create-react-app - organizing types in a separate file

I'm currently developing a project using Create React App with TypeScript (create-react-app myapp --typescript) In my App.tsx file, I have written some TypeScript code that I want to move to an external file. I have tried creating App.d.ts, index.d.t ...

Importing the .css file within a React component for dynamic styling

In my component, I am trying to dynamically load a .css file based on the result of an AJAX call in componentDidMount(). I have attempted adding a <link> element in the render return (which did not work), and also tried injecting the tag directly int ...

Working with PHP to transfer toggle switch information to JSON

I'm currently experimenting with a combination of HTML, JavaScript, and PHP on a single page. My goal is to update a JSON file with either 0 or 1 based on the toggle switch state change. I seem to be close to achieving this functionality, but upon rel ...

Clicking 'Submit' triggers a continuous loop upon loading

I set up this form to automatically submit once the page has finished loading. However, I seem to be encountering a problem where the page gets stuck in a continuous loop of reloading. HTML <body onload="document.getElementById('filters').su ...

What is the best way to implement rate limiting for asynchronous API calls within a specific timeframe?

I have a project that requires me to make over 500 calls simultaneously from my NodeJS server to a third-party server. The issue is that the third-party server has a restriction of only allowing a maximum of 50 calls per second. Can someone assist me in im ...