"Utilizing the splice method to insert an element at specified indexes within an

        const list = []
        const obj = {
          name: '',
          mobile: ''
        }
        _.forEach(errors, (value, key) => {
          // eslint-disable-next-line no-debugger
          // debugger
          const field = key.split('.')[2]
          const index = key.split('.')[1]
          obj[field] = value[0]
          list.splice(index, 1, obj)
          console.log(obj)
        })

This code snippet showcases the current progress of my work. Following this, you will find a screenshot displaying the logs for each obj variable.

https://i.sstatic.net/BALaM.png

The main objective is to incorporate that object into the specified index within the list variable.

However, upon completion of the loop, what I end up with is illustrated in the subsequent image:

https://i.sstatic.net/jvZIy.png

It appears that the last item in the loop overrides all the content in the list array.

For reference, here are the available indexes:

https://i.sstatic.net/q7mXp.png

In essence, I am striving to have the obj inserted at a specific index within the existing list array.

EDIT

The structure of the errors variable is demonstrated below:

https://i.sstatic.net/iWE2h.png

My aim is to transform it into something similar to the following:

list = [
   { name: 'name error message here', mobile: 'error message here' },
   { name: 'name error message here', mobile: 'error message here' },
   { name: 'name error message here', mobile: 'error message here' },
   { name: 'name error message here', mobile: 'error message here' }
]

Answer №1

Are you satisfied with the result?

function convert(data) {  
  return Object.entries(data).reduce((p, [key, [message]]) => {
    const keyParts = key.split('.')
    p[keyParts[1]] = p[keyParts[1]] || {}
    p[keyParts[1]][keyParts[2]] = message
    return p
  }, [])
}

const data = {
  'contacts.0.mobile': ["Error. Mobile number is a required field."],
  'contacts.0.name': ["Error. Contact name is a required field."],
  'contacts.1.mobile': ["Error. Mobile number is a required field."],
  'contacts.1.name': ["Error. Contact name is a required field."]
}
console.log(convert(data))

Alternatively, you could use a regular expression with named capture groups:

   
const PATTERN = /contacts.(?<index>\d+).(?<type>\w+)/

function convert(data) {  
  return Object.entries(data).reduce((p, [key, [message]]) => {
    const { index, type } = PATTERN.exec(key).groups
    p[index] = p[index] || {}
    p[index][type] = message
    return p
  }, [])
}

const data = {
  'contacts.0.mobile': ["Error. Mobile number is a required field."],
  'contacts.0.name': ["Error. Contact name is a required field."],
  'contacts.1.mobile': ["Error. Mobile number is a required field."],
  'contacts.1.name': ["Error. Contact name is a required field."]
}
console.log(convert(data))

Answer №2

The issue arises from declaring the obj variable outside the forEach loop, causing all elements in the errors object to reference the same object. Therefore, any updates made to obj will affect all elements since they are pointing to the same object. To have each index contain its own unique object, adjustments need to be made in the code structure.

const errors = {
  "contacts.0.mobile": ["Error. Mobile number is a required field."],
  "contacts.0.name":   ["Error. Contact name is a required field." ],
  "contacts.1.mobile": ["Error. Mobile number is a required field."],
  "contacts.1.name":   ["Error. Contact name is a required field." ],
};

const list = [];
_.forEach(errors, (value, key) => {
  const [, index, field] = key.split(".");
  if (!list[index]) list.splice(index, 1, {name: "", mobile: ""});
  list[index][field] = value[0];
});

console.log(list);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b37343f3a28331b6f756a6c75696b">[email protected]</a>/lodash.min.js"></script>

The solution presented ensures that a new object is created for each distinct index encountered during the execution of the code.

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

Error: The request to /api/auth/login in Postman failed unexpectedly

As I am working on developing an app using node.js and express, I encountered an error while making post requests in Postman. Cannot POST /api/auth/login%0A Below are the details of my app's structure along with the files involved: app.js const ex ...

Supply mandatory argument along with varying arguments to the function

I have a function that requires one parameter and a dynamic set of additional parameters. I am passing an array of blobs to the function. Below is a simplified version of the function: function test(directory, blob0, blob1) { for (var argumentIndex = 1; ...

Returning a value with an `any` type without proper validation.eslint@typescript-eslint/no-unsafe-return

I am currently working on a project using Vue and TypeScript, and I am encountering an issue with returning a function while attempting to validate my form. Below are the errors I am facing: Element implicitly has an 'any' type because expression ...

AngularJS text area not displaying HTML content

In my Ionic's App, I have a textarea that is used for creating or editing messages. However, I am encountering an issue where the textarea does not render HTML tags when trying to edit a message. I attempted solutions such as setting ng-bind-html and ...

Any ideas on how to resolve this ajaxToolkit issue?

Just for your reference, here's what I'm trying to achieve: https://i.stack.imgur.com/GYaNz.jpg Error 1: Unknown server tag 'ajaxToolkit:CalendarExtender'. <ajaxToolkit:CalendarExtender FirstDayOfWeek="Monday" PopupPosition="Botto ...

Updating a deeply nested value with React's setState

Dealing with a deeply nested object in my React state has been quite the challenge. The task at hand is to modify a value within a child node. Fortunately, I have already identified the path leading to the node that needs updating and I am utilizing helper ...

Before the async function, make sure to set the value using React's useState

Exploring the world of react context api for the very first time. Below is my react code utilizing the context api: const [valChanged, setValChanged] = useState(false); async function modalSave() { await setValChanged(true); // STEP 1 await o ...

Providing data in response to a completed form submission

As a beginner, I'm attempting to accomplish the following task: a user selects options from three dropdown menus within a form, and the chosen values are then sent to another file for processing. action="process.php" method="post" In the processing ...

An effective way to verify if a record has been successfully updated is by utilizing Sequelize's

Within this snippet of code, I made an update to a specific record in the IPAdress model. What is the best way for me to verify if the record has been successfully updated or not? let IPAdress = await model.IPAdress.update(data,{ where: { id } }); ...

What is the process for selecting the Node version when installing with .nvm?

I am having an issue with nvm in the terminal. When I try to run npm install <something>, it always installs the package in node version 9.4.0, regardless of the version set using nvm. Even after switching to node version 10.15.3 using nvm use v10.1 ...

Leverage the response data from the first AJAX call as a variable for the second

I have a script that performs two ajax calls - the second one is nested within the success handler of the first. However, I need to utilize the data retrieved in the first success handler as an additional variable to send in the second ajax call, and then ...

Showing error messages in Angular when a form is submitted and found to be invalid

My form currently displays an error message under each field if left empty or invalid. However, I want to customize the behavior of the submit button when the form is invalid. <form #projectForm="ngForm" (ngSubmit)="onSubmit()"> ...

After loading Google Maps, initiate an AJAX request

Is there a way to determine if Google Maps has finished loading? I need to send an Ajax request once the map is fully loaded. Currently, I am displaying a group of users on a map with info windows. However, the browser becomes unresponsive due to the larg ...

Node.js Export Module Error - importance of separating concerns

I have been attempting to implement separation of concerns by using export module. Everything functions properly when used without separating concerns, but as soon as I try to import generateUrlArray() from const db = require('../db'), nothing se ...

The Ajax response is coming back with a null value, but upon inspecting the network response

I'm facing a strange issue where one specific value from an ajax json response is showing up as an empty string, while all other values are appearing correctly. An unusual aspect of this problem is that the network panel displays the correct value in ...

What is the best way to automatically close a parent popup window when the child popup is

Currently, I am developing a web application using Angular that requires managing nested popups. Specifically, in my scenario, I initiate Popup 1 and from within that popup, I trigger another popup (Popup 2) upon clicking "delete." My goal is to ensure tha ...

Using a JavaScript function, transmit information through an Express response

I am working on sending an application/javascript response from my Express server, utilizing data retrieved from MongoDB. This response is intended for loading content on a third party website. All components of the process have been developed, and now I ...

Tips for establishing a connection between a Node.js application and PostgresSQL hosted on Heroku

I have utilized Vue, webpack, Express and PostgresSQL in the development of my app. After deploying my app to Heroku, I established a PostgresSQL database on the platform. In the image below, you can find the Database Credentials: https://i.sstatic.net/aI2 ...

Issue with long text in a resizable table using jQuery tablesorter 2.31.1

My issue is that when I try to resize the columns in tablesorter, they snap back into place. The column width set with resizable_widths does not apply correctly until a column is manually resized. Despite setting the width of all cells to 120px, any cells ...

Improve navigation by integrating jQuery validation to resolve input errors seamlessly

I have been working with the jQuery validation plugin and Bootstrap. I recently added a fixed navigation bar at the top of the page using Bootstrap CSS. However, I encountered an issue where the fixed navigation was overlapping with the error message for i ...