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

How to eliminate an entry in a list of dictionaries in Python when the value is an empty string, "null", or None

I'm dealing with a JSON object that has unwanted values such as "null", "", and None. If these values are present in the object, I want to remove the entire object. >>> json.dumps(event, indent=4) "event" = { "status": "COMPLETED", ...

Utilizing Jquery to enhance slide image transitions with navigational links

As a newcomer to jQuery, I am attempting to create a slider using jQuery. Here is the script I have so far: $(function() { var bgCounter = 0, text = [ 'some html code here', 'some html code here', 'some ...

Find a string that matches an element in a list

I currently have a list structured like this let array = [ { url: 'url1'}, { url: 'url2/test', children: [{url: 'url2/test/test'}, {url: 'url2/test2/test'}], { url: 'url3', children: [{url: & ...

Access in-depth data by clicking on a map to get detailed information

Recently, I took on the challenge of managing a golf club website after the original creator had to step away. One urgent issue I need to address is fixing a malfunctioning flash animation that provides information about each hole on the course. My plan is ...

Improving an HTML list with JavaScript

My current project involves a JavaScript game similar to Scrabble. I want users to be able to create new words in the game, and have those words added to a list that is displayed on the page within a div element. However, I'm struggling to understand ...

On smaller screens, the top placement of right sidebar links is necessary

Our website layout is organized into 3 main sections: the top part contains the main menu, followed by the main content and a sidebar specific to each page. The main content and sidebar are structured using bootstrap col-* classes. On small screens, I en ...

I'm having trouble with my basic routing set up and I'm struggling to understand why it's not working

I'm currently working on a node tutorial and facing some challenges with my routes.js file. Previously, everything was functioning well today as the Node server was able to read the file. However, it seems to be ignoring it now for some unknown reaso ...

Oops! RangeError [MESSAGE_CONTENT_TYPE]: The content of the message must be a string that contains at least one character

Can someone help me troubleshoot my regular send command? I keep encountering an error message even after following suggestions from previous answers. Here is the error: RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty string. at ...

Removing automatically assigned ID information in Firestore can be achieved by following these steps:

async created () { const sn = await db.collection('forms').get() sn.forEach(v => { const { title, content } = v.data() this.forms.push({ title, content, id: v.id }) console.log(v.id) }) }, del () ...

The error message "Uncaught TypeError: Cannot read property 'length' of undefined" is commonly encountered in asp.net while using dataTables with zero config

I am encountering an issue with dataTables in my ASP.NET webforms application. The table is generated in the codebehind at Page_Load() and works fine on other pages, but for some reason, I am getting an error message on one specific page: "datatables.min.j ...

Is it possible to modify the parameters of a function by utilizing a MethodDecorator without affecting the "this" value?

Consider a scenario where you need to dynamically modify method arguments using a decorator at runtime. To illustrate this concept, let's simplify it with an example: setting all arguments to "Hello World": export const SillyArguments = (): MethodDec ...

"Keeping your HTML content up-to-date with AngularJS dynamic updates

I've noticed that when I upload changes to my AngularJS HTML partial files, there is a caching issue where the old data is displayed. It takes a few refresh actions before the changes become visible. Is there a way to make these changes appear immedi ...

How to eliminate duplicate items in an array using various criteria

I have an array arr that needs to be cleaned up by removing duplicate objects with the same e_display_id and e_type as P. In this scenario, only objects with status==='N' should be considered. Here is the input array arr: let arr = [ { e_type ...

updating the row of an html table with elements from a javascript object

I am faced with the task of dynamically adding rows to a table based on the number of elements in my JavaScript object. The object consists of keys and arrays of values. userobject={ ID: [1,2,3] IP_Address: ["12.21.12 ...

How can you continuously calculate and show the total quantity of items in a list?

Currently, I have lists set up in my sidebar and I'm looking to include a label displaying the number of items within each list. To provide a better understanding of what I'm aiming for, I've put together a JSFiddle demonstration at the fol ...

Locate a specific value within an array of objects and display it

Data : const areas = [ { "ID":"4131", "RID":"f1438b", "Name":"City" }, { "ID":"6266", "RID":& ...

Is there a way for me to retrieve SCSS color variables within the javascript of a Vue template?

I have a unique challenge in my application involving a component called Notification. To bring notifications to other components, I utilize the mixin method toast('message to display', 'color-variable'). My goal is to set the backgroun ...

What is preventing the function from successfully compiling text from various files that are uploaded using the HTML5 file reader into an array?

My current challenge involves attempting to upload two text files using the HTML 5 file reader. While I can successfully get the files into an array, encountering difficulty arises when trying to return that array from the function. One solution could be ...

Reorganize the array or generate a new array using the indexes of the objects

I have a specific object that I need to render into table rows and cells using JSX... { "0": [ { "colIndex": 0, "data": { "richTextModule": "Data row 1 cell 1" } }, ...

Angular not successfully passing ID in for loop

I am trying to pass the res[i].id value to my ArrayList while maintaining the sequence. Can anyone help me understand why 809 and 806 are not getting added to the arrayList correctly? 0: {id: 0, ArrayListID: 809, VarName: "TEST001A"} 1: {id: 0, ...