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

Exploring CountUp functionality with Vue framework

I'm still getting the hang of Vue and recently completed my first project following a tutorial. This project is my first solo endeavor. Currently, I am working on a basic page to display the scores between two teams. The scores are retrieved from an ...

Node.js and Express causing Openshift to enter a crash loop back-off situation

I've recently ventured into setting up a server for dynamic web pages using Openshift. I put together a basic node.js/Express template solely to establish a connection to Index.html for testing purposes. However, whenever I attempt to execute the code ...

Instead of scrolling through the entire window, focus on scrolling within a specific HTML element

I currently have the following elements: #elementA { position: absolute; width: 200%; height: 100%; background: linear-gradient(to right, rgba(100,0,0,0.3), rgba(0,0,250,0.3)); z-index: 250; } #containerofA { position: fixed; ...

expanding the input and duplicating the outcomes

I'm attempting to clone and add values to results in my project. Here's the link to what I have so far: http://jsfiddle.net/QNP3r/175/ Currently, it is functioning adequately with a table element. However, I'd like to make it work with a di ...

Can you explain the significance of npm WARN excluding symbolic link?

Could you please explain the meaning of npm WARN excluding symbolic link? Also, any advice on how to resolve this issue? ...

Retrieve the child nodes from the array and organize them into a

Given an array of regions, where the highest region has key: 10 and parent_id: null, the goal is to restructure this array in order to return a tree representation. The desired regions tree structure for input [10] should be: Egypt Zone 1 Tagamo3 Giza H ...

What is preventing Angular from letting me pass a parameter to a function in a provider's useFactory method?

app.module.ts bootstrap: [AppComponent], declarations: [AppComponent], imports: [ CoreModule, HelloFrameworkModule, ], providers: [{ provide: Logger, useFactory: loggerProviderFunc(1), }] ...

What is the best way to pass a specific property from a parent component to a child component in Angular when a button is clicked?

Hey there, I'm looking for a way to pass a single property (groupId) from a parent component to a child component. In this case, my child component is using ngx-bootstrap modal. Is there a solution available for this scenario? Essentially, I need to i ...

What does an exclamation mark signify in Angular / Type Script?

Being a newcomer in the world of front end development, I am currently teaching myself Angular (11.2.10). While exploring a sample project, I noticed this particular piece of html template code written by another person and utilized in multiple places: < ...

I am facing errors while running npm run build in my Vue CLI project, however, npm run dev is running smoothly without

I am encountering an issue when running npm run build as it generates a series of errors, whereas npm run dev runs smoothly without any errors. I have attempted to resolve this by modifying the public path in webpack.config.js to ./dist, but unfortunately ...

"Using Nightwatch.js to Trigger a Click Event on a Text Link

My goal is to use Nightwatch for testing the login process by clicking on a log in text link. I came across this helpful article: How to click a link using link text in nightwatch.js. The article suggested using the following code: .useXpath() // ever ...

The html-docx-js package generates incomprehensible text

Has anyone successfully utilized html-docx-js recently? I attempted the following code snippet: var newHTML = "<!DOCTYPE html><html><head lang='en'><meta charset='UTF-8'><title>Report</title& ...

Tips for converting an object into parameters for ng-include

What is the best way to create a serialized array of objects that can be used as parameters for ng-include in order to dynamically load data from the server? Using Angular controller and params with requests: app.controller("MyCtrl", function($scope) { ...

Should the index.js file in Next.js serve as the homepage or solely as the initial starting point?

Should I integrate my homepage directly into the index.js file, or create a separate "home-page.js" file in the pages directory? Is index.js just for initializing the application, or can it serve as a standalone page? Alternatively, should I have index.j ...

Navigating Angular modules - a different perspective

I am brand new to angular routing and lazy loading modules. ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'login-admin/admin-dashboard' Error: Cannot match any routes. URL Segment: 'login-admin/admin-d ...

Having trouble displaying Ad-Gallery Loader.gif?

Having trouble with an image gallery I found at . The loader.gif image isn't showing up in IE9, just a red X. Being new to JavaScript, I'm struggling to fix this issue located at the top of the JavaScript file. (function($) { $.fn.adGallery = ...

Nodejs: The JSON.stringify method is automatically rounding the numbers

I am encountering a strange issue. When I call the credit card processor (CCBILL) with a payment token, they return a subscription ID. For example, 0124058201000005323 should be returned but what I receive is 124058201000005330, indicating that it has been ...

Searching within a container using jQuery's `find` method can sometimes cause jQuery to lose control

I am trying to extract information from an input field within a table in a specific row. Here is the code I am using: var myElements = $('#myTable tbody').find('tr'); console.log(myElements); This correctly displays the items in the ...

Is the tab not displaying correctly when using Bootstrap 5 button functionality?

With Bootstrap 5, I have a modal that contains two tabs for login and register. However, I am facing an issue where the tab is not displaying correctly based on the button click. The desired behavior is that clicking on the login button should activate th ...

Using global variables for mocha testing (and babel setup)

Currently, I am developing a library using es6 and transpiling it with babel via webpack and npm. However, I have encountered an issue where my library has a dependency on some code that cannot be modified but is required for my library to function properl ...