Tips for updating a custom value in an array with a for-each loop

I am working with an array where I need to create a function that will loop through the array and reset the 'val' for all items except the second one (index 1). I attempted to use the forEach method but I am struggling with the implementation.

names = [
{
  name: 'first',
  inputType: 'number',
  val: void 5
},
{

  name: 'second',
  inputType: 'number',
  val: void 2
},
{
  name: 'third',
  inputType: 'text',
  val: void 3
}
]

Here is what I have tried:


resetValues() {
 let names = this.names
 names.forEach((name:any, index:number)=>{
 if(index===1){
   name[1] = name[1].val
 } else{
   name.val = ''
 }
})
}

Answer №1

It appears that you are looking to modify the val property by setting it to an empty string using a forEach loop, excluding index 1:

let items = [
  {
    name: 'first',
    inputType: 'number',
    val: void 5
  },
  {
    name: 'second',
    inputType: 'number',
    val: void 2
  },
  {
    name: 'third',
    inputType: 'text',
    val: void 3
  }
];
console.log('Prior', items);

function updateValues()
{
 items.forEach((item, index)=>
 {
  if(index !== 1)
   {
    item.val = '';
  } 
 });
}

updateValues();
console.log('Afterward', items);

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

Leverage AngularJS within your Chrome extension

Attempting to integrate AngularJS into a Chrome extension, I encountered the following error: Error: SECURITY_ERR: DOM Exception 18 Error: An attempt was made to break through the security policy of the user agent. at new listConnection manifest.json ...

Can someone help me figure out the best way to locate a material-ui slider within a react

I am seeking to incorporate multiple material-ui sliders into a single react component that share a common event handler. However, I have encountered difficulties in identifying which slider triggered the event. Despite referring to the API documentation, ...

Shut down a pop-up overlay

I've been facing a challenge in implementing greasemonkey to automatically close a modal when the "x" button is clicked. Allow me to share with you the code snippet for the webpage: <div class="modal-header"> <button type="button" class="clo ...

Utilizing Regular Expressions in AngularJS to validate name, a 10-digit mobile number, and a 12-digit number through the ng-blur event and match

I am struggling to validate the three inputs mentioned above and having trouble using the right functions. Can someone please assist me with this? Here is the HTML code for the 3 inputs: <input id="name" ng-model="user.name" ng-blur="checkIfNameIsVali ...

Is there a way to undo the click event in Javascript?

Is there a way to revert back to the initial position after clicking? I successfully changed the x icon to a + icon on click, but now I'm struggling to reverse that action. I've tried using MOUSEUP and DBLCLICK events, but they aren't ideal ...

TypeScript - Determining the type of an array with multiple data types

When dealing with an array of union, checking the typeof value can be done this way: //case 1 function something1(a1: Array<number | string | boolean>) { for (const v of a1) if (typeof v === "number") v; //v is number ...

The function Geometry.center() has not been used

Within my code, I am working with a BufferGeometry that undergoes changes in vertices and colors periodically. To manage this, I create a new buffergeometry if more space is required for vertices; otherwise, I reuse the existing one by adjusting its drawRa ...

Establishing a connection between a frontend Javascript client and a backend Node.js/express server

Recently, my close friend successfully created a working client website using Javascript. Meanwhile, I have managed to get my server code up and running smoothly, extracting specific data through MySQL. We are now seeking some advice on how we can link t ...

Using Selenium Webdriver to target and trigger an onclick event through a CSS selector on a flight booking

I've been running an automation test on the website . When searching for a flight, I encountered an issue where I was unable to click on a particular flight. I initially tried using Xpath but it wasn't able to locate the element when it was at th ...

Attempting to implement usedispatch hook in combination with userefs, however, encountering issues with functionality

I've been exploring the Redux useDispatch hook lately. I created a simple app for taking notes in a todo list format. However, I am facing an issue with useDispatch as it's not working for me and I keep encountering this error: Module build faile ...

Deleting items from a JavaScript object array in Angular using TypeScript can be achieved by using various methods and

Here is the structure of my object array: 0: {Name: "Albert", Id: 32} 1: {Name: "George", Id: 34} 2: {Name: "Jane", Id: 35} Although the request is successful, the array remains unchanged. However, upon refreshing the app, the item (student) is deleted. ...

Displaying text when hovering the mouse over an element

Currently, I am working on a task that involves making a background image disappear and then revealing some text with a link in the div. Although I have managed to make the image disappear upon mouseover, I am struggling to display the text. Below is my cu ...

Web audio: setTimeout slows down when mobile screen is turned off

In response to Yogi's feedback (refer to the discussion on "setTimeout" and "throttling" in https://developer.mozilla.org/en-US/docs/Web/API/setTimeout ), I attempted to enhance performance by integrating an AudioContext. document.addEventListener(&ap ...

Instructions for passing a JavaScript variable to a PHP MySQL database

I am attempting to integrate a JavaScript variable into PHP MySQL, but I'm encountering issues with the insertion. Currently, it is being inserted as <javascript>document.write(window.outerWidth); </javascript> x <javascript>document ...

What is the solution to the error message "Cannot assign type 'string' to type '{ question: string; answer: string; }[]"?

I have searched for solutions, but I am still struggling with this issue: when using i18n, I encounter a TypeScript error "Type 'string' is not assignable to type '{ question: string; answer: string; }[]'" and "Error: text.map is not a ...

Changing the ngModel value within ngFor loop

I am working on a project where I need to display a list of grades from an object called 'grades'. Additionally, I want to integrate a slider component for each grade, with the value of the slider corresponding to a predefined list. However, it s ...

Is there a way I can create an object in JavaScript by using an array of values as parameters instead of having to manually list them out?

Can I achieve this? My goal is to develop a universal factory function that can generate different types of factories with some commonalities. I aim to pass arguments as an array to the base factory, which would then potentially create a new object instanc ...

An effective method for selecting data within table rows using jQuery

I have a table with multiple rows that follow the same format: <tr role="row" class="even"> <td><input type="checkbox" id="valj4"></td> <td>Generell grupp</td> <td><a href="/Home/DeviceDetails?uuid=2b9fe5 ...

Pros and Cons of Using HTML5 Mode versus Hash Mode in AngularJS

When using AngularJS 1.3, it is necessary to include the <base> tag in HTML5 mode. This led me to consider the pros and cons of HTML5 mode versus Hash mode. In Hash mode, the major drawback is that URLs can appear unattractive and may not be easy fo ...

Whenever I try to retrieve data from MongoDB using Node.js, I consistently encounter a timeout error

Currently, I am in the process of developing a website using React.js for the front end, Node.js for the back end, and MongoDB as the database. Dummy data has been inserted into the database which can be viewed https://i.sstatic.net/YOzCB.png. The database ...