Switch out two for loops with the find or filter method in JavaScript

In my unique approach, I am showcasing a variety of product details lists based on availability in various shops. To achieve this, I have implemented the following method.

for (let i = 0; i < this.prodList.length; i++) {
  let setContent = false;
  for (let j = 0; j < res.data.length; j++) {
    if (res.data[j].product === this.prodList[i].value) {
      this.detailList[i] = {
        product: this.prodList[i].value,
        content: res.data[j].content,
        shopName: res.data[j].shopName
      };
      this.formData.addressList[i] = {
        product: this.prodList[i].value,
        content: res.data[j].content,
        shopName: res.data[j].shopName
      };
      setContent = true;
      break;
    }
  }
}

I am curious about alternative methods such as using find or filter instead of a traditional for loop. How can I implement these to enhance efficiency?

Answer №1

The outcome is a representation of the prodList in the form of a map, and the nested operation carries out a function similar to 'find', thereby...

this.detailList = this.prodList.map(prod => {
  let resProd = res.data.find(r => r.product === prod.value);
  return {
    product: prod.value,
    content: resProd.content,
    shopName: resProd.shopName
  };
});

It appears that the code is initializing formData.addressList, as an array containing duplicated objects. This initialization could be integrated within the map function or implemented separately as another map.

this.formData.addressList = this.detailList.map(o => ({ ...o }));

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

Tips for sending <p> data to a router function with HTML

I am currently working on a page where users are presented with a list of unverified accounts, each containing its own form element. Each form has a "submit" button that triggers a POST call to /verify. However, I am facing an issue where the data within t ...

What is the best way to keep track of a checkbox's value after unchecking it and then returning to the same slide?

Issue: By default, the checkbox is always set to true in the backend code. Even if I uncheck it using JavaScript, the value remains as true when switching between slides. Desired Outcome: If I uncheck the checkbox, the updated value should be saved so tha ...

Implementing an array of functions on an array of elements based on their positions

Imagine the scenario: def x_squared(x): result = x * x return result def twice_x(x): result = 2 * x return result def x_cubed(x): result = x * x * x return result x_values = np.array([1, 2, 3]) functions = np.array([x_squared, t ...

Proportional fluid image grid with responsive design

After implementing various media queries, I've managed to create an image grid using Bootstrap 4+ that looks great on specific devices and layouts. Here's the reference code: .cmd-three-img-container { position: relative; margi ...

When validated, the Yup.date() function seamlessly converts a date into a string without including the timezone

Currently, I am integrating Yup with react-hook-form and have defined the following schema in Yup: const validationSchema = Yup.object({ installation: Yup.string().nullable().required("Required"), from_date: Yup.date() .max(new Date(), "Can ...

Encountered an issue during the Jest test where the error message states 'Cannot call Class constructor Stack without using the keyword 'new''

I have encountered an issue with my Jest test for an AWS CDK configuration import { expect as expectCDK, matchTemplate, MatchStyle } from '@aws-cdk/assert'; import * as cdk from '@aws-cdk/core'; import { KmsMultiregionPrincipalKey } fro ...

Creating a unique Vue.js modal window for every individual product

Currently, I am in the process of creating a small online store using Vue.js. Within this store, I have a variety of products each with unique names and prices. In order to provide more information about each product, I have included a "Details" button. M ...

The function persists in outputting a true result, despite the fact that it is expected to output

Currently, I am working on a NextJS project where I have a client-side form. I've been attempting to implement validation for the form by creating a separate function called validateForm(). However, no matter what input is provided, the function alway ...

Issue with VueJs and ChartJs not displaying custom options when making an API call

Having trouble populating my chart with data from the API. Despite setting extraOptions for my chart, it defaults to default options when rendered. Here is the component code: import { Bar, mixins } from 'vue-chartjs'; export default { name: ...

Customizing Geonames JSON Ajax Request

Having found the code I needed from a sample website, I am now seeking help to customize it to only display results from the USA. This is the current code snippet: $(function() { function log( message ) { $( "<div>" ).text( message ).pr ...

Unable to send POST request (including data) using event trigger from an external component

I'm currently facing an issue where a click event in one component is triggering a method in another, but the data that should be passed in my POST request isn't being sent. Interestingly, when I test the functionality by calling the method dire ...

The React component continuously refreshes whenever the screen is resized or a different tab is opened

I've encountered a bizarre issue on my portfolio site where a diagonal circle is generated every few seconds. The problem arises when I minimize the window or switch tabs, and upon returning, multiple circles populate the screen simultaneously. This b ...

Exploring a collection of objects in an Angular 2 component

Can someone please assist me in identifying what I am doing wrong or what is missing? I keep getting an undefined value for `this.ack.length`. this._activeChannelService.requestChannelChange(this.selectedchannel.channelName) .subscribe( ...

Ways to retrieve data from an AJAX success callback function

Within my front end JavaScript application, I need to execute an ajax request in order to retrieve data from the server. Once this data is acquired, I aim to display it within the view. var retrievedData; $.ajax({ url:"/getDataFromServer.json", ty ...

Tips for creating boxes with clearly defined edges on shared sides using three.js

When I draw boxes with common sides, I don't see the common edges, but rather perceive them as a single object even though there are 25 boxes: https://i.sstatic.net/gE8FW.png function box(scene, x, y, z, size) { const points = []; ...

JavaScript encounters a parsing error when dealing with an async function

Ever since I developed a node.js web application, I've been utilizing MSSQL for the database. To streamline SQL functions, I crafted functions (sql.js) to handle all the necessary queries. Furthermore, I set up async function handlers (controllers.js) ...

Using ASP.NET MVC to map FormData with an array to a model class

I am currently facing an issue with mapping a list of objects in a FormData to my ASP.NET MVC Model class at the controller. I have successfully sent the FormData over to the server-side, but I am unable to bind any value. Can someone provide guidance on h ...

I keep getting redirected to a blank page by JS

I've created a JavaScript script that smoothly fades in the page when a user enters it and fades out when they click a link to another page. The script is working as intended, but I'm facing an issue with anchor links on the page. Whenever I clic ...

Tips for creating a dynamic curved SVG path

I'm looking to draw a black border only along the inside of this SVG. I've tried adding stroke and setting the stroke-width, but that applies the border to the entire SVG. Is there a way to limit the stroke to a certain point within the SVG? d ...

Can webpack integrate React components from a package and then recompile the package?

I am currently in the process of creating an npm package to standardize my layout components that are based on geist components. Initially, I attempted to use the npm package as a local component, but encountered a webpack loader error when trying to read ...