Assign a specific value to each object

Receiving data from the backend in a straightforward manner:

this.archiveService.getRooms(team).subscribe(
  res => {
   this.form = res;
    this.form.forEach(el => {
     el.reservation.slice(-6).match(/.{1,2}/g).join('/');
    });

  },
  error => {
    console.log(error);
  }
)

this.form represents an object where I extract reservation numbers and remove unnecessary parts using regular expressions. After preparing the value, it is assigned back to this.form for displaying with *ngFor in a table.

The challenge lies in assigning each value from the forEach loop back into this.form.

Answer №1

After consulting the documentation, it is evident that the JavaScript slice method does not alter the original array.

Instead, it returns a new array with the extracted elements.

To address this issue, you have two options: either utilize the splice method, which functions as described below:

The splice() method alters an array by removing or replacing existing elements and/or adding new elements. If you wish to extract part of an array without modifying it, consider using slice().

this.form.forEach(el => {
     el.reservation.splice(-6).match(/.{1,2}/g).join('/');
    });

Alternatively, you can reassign the value using the slice method like so:

this.form.forEach(el => {
     el.reservation = el.reservation.slice(-6).match(/.{1,2}/g).join('/');
    });

Illustrative Example

const myArr = [1,2,3,4,5,6,7,8,9,10]

const returnVal = myArr.slice(0,5)

console.log(`Value returned by slice : ${returnVal}`)
console.log(`Current array : ${myArr}`)

console.log('------------------')

const myArr2 = [1,2,3,4,5,6,7,8,9,10]

const returnVal2 = myArr2.splice(0,5)

console.log(`Value returned by splice : ${returnVal2}`)
console.log(`Current array : ${myArr2}`)

Answer №2

The main purpose of using the .forEach() method may not always meet your expectations.

If you find yourself stuck in a mundane routine and looking to explore more advanced options, consider exploring Array.prototype.forEach() for more flexibility.

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

Failed to load module chunk: Please update to angular 7

I am encountering an issue with my application hosted on IIS after upgrading to Angular 7. The error message "Loading chunk module failed" indicates that instead of fetching files from the dist/ folder, it is attempting to fetch them from the root folder. ...

What's the Best Way to Add a Custom Flag to the `nx angular serve` Command Without Triggering an Error?

When running the nx angular serve command, I want to add my custom flag (-t example). But when I try this, I get an error message from nx that says: 't' is not found in schema To address this issue, I plan to capture this flag in proxy.mjs an ...

After submitting the form, Axios sends multiple requests simultaneously

Recently, I embarked on a small project that involves using Laravel and Nuxt Js. The main objective of the project is to create a form for adding users to the database. Everything seems to be progressing smoothly, but there's a minor issue that I&apos ...

The argument type 'MouseEvent<HTMLButtonElement, MouseEvent>' cannot be assigned to the parameter type 'HTMLElementEvent<HTMLButton>'

Here is the code snippet that I am currently working on and encountering an error in the console: type HTMLElementEvent<T extends HTMLElement> = Event & { target: T; } toggleHandler = (e: HTMLElementEvent<HTMLButtonElement>) => ...

Encountered an error while using npm install --legacy-peer-deps: Debug Failure. SyntaxKind: Unknown went unhandled

When attempting to execute the command npm install --legacy-peer-deps, I encountered an error. The specific error message is as follows: Error: Error on worker #1: Error: Debug Failure. Unhandled SyntaxKind: Unknown. at pipelineEmitWithHintWorker (port ...

Guide on positioning components to the right side of the NavigationDrawer in Vuetify with VueRouter

Working on my VueJS project, I've implemented a system to display content based on the user login using Firebase and Vuex state management. When a user is logged in, the content is shown using the v-if directive. Currently, I have successfully placed ...

What are the steps to determine if a radio has been examined through programming?

In my form page, users can input an ID to fetch profile data from a MySQL database using AJAX. The retrieved data is then displayed in the form for editing. One part of the form consists of radio buttons to select a year level (e.g., "1", "2", "3", etc). ...

The appropriate method for showcasing cards within lists, such as in the platform Trello

I'm in the process of developing a project similar to Trello, but I'm facing some challenges on how to proceed. Initially, I created an 'init' function within my AngularJS Controller to handle HTTP requests: $scope.loadLists(); ...

"Creating a new element caused the inline-block display to malfunction

Can someone explain why the createElement function is not maintaining inline-block whitespace between elements? Example problem First rectangle shows normal html string concatenation: var htmlString = '<div class='inline-block'...>&l ...

What is the best way to open the index.html file in electron?

I'm currently developing a cross-platform app using electron and Angular. As of now, the code I have for loading my index.html file looks like this: exports.window = function window() { this.createWindow = (theBrowserWindow) => { // Create ...

Get rid of the folder from the URL using an <a> tag

I have both an English and French version of my website located at: *website.com/fr/index.php *website.com/index.php Currently, I have a direct link to switch between the two versions: -website.com/fr/index.php -website.com/index.php. However, I ...

transform array elements into an object

I encountered the following code snippet: const calcRowCssClasses = (<string[]>context.dataItem.cssClasses).map( (cssClass) => { return { [cssClass]: true }; } ); This code block generates an array of objects like ...

Tips for accessing the value of a dynamically created textbox using JavaScript

Hello everyone, I have a couple of questions that I need help with. I am currently working on developing a social networking website similar to Facebook. On this platform, there are multiple posts fetched from a database. However, I am facing an issue w ...

Unable to modify the logo images in React

I'm struggling to figure out how to make my images (favorite.svg and favorite-white.sgv) change every time the button is clicked in React. I've tried various solutions but it's proving to be quite challenging. When the button is clicked, I ...

Incorporating <span> elements into a comma-separated list using Jquery on every other item

When I receive a comma-separated list of items from a database and insert them into a table cell, I want to apply alternating styles to make it easier for users to distinguish between them. For example: foo, bar, mon, key, base, ball I'm looking to ...

Moment.js generated an error due to an unhandled promise rejection warning

I'm trying to determine if my current timestamp is equal or greater than a certain value, but I keep encountering errors. Here's my code with the error: {...} exports.validaforgotpass = async (req, res) => { {...} const results = aw ...

Add items to a fresh record using Mongoose and Express

In my model, I have an array of objects that I want to populate with new items when creating a NEW document. While I have found information on how to achieve this using findAndUpdate, I am struggling to figure out how to do it with the save() method. This ...

What is the best way to determine if an object.property is defined in Angular 2?

Is there a similar function in Angular 2 to angular.isDefined from Angular 1? I have tried using the safe navigation operator ?., which is only supported in templates. ...

Tips for iterating through an array of images and displaying them in a React component

I am working on a project in my react app where I have 5 images that I want to cycle through indefinitely. The goal is to create an animation where a light bar appears to be constantly moving. The shifting dot in each image will give the illusion of movem ...

Enhancing User Interfaces with JQuery UI Widgets and Dynamic AJAX Calls

Currently involved in geolocation and mapping work, I am creating a JQuery widget to ensure that the code is portable for future projects. However, I have hit a roadblock when it comes to making an AJAX request. Below are a couple of methods from my widge ...