Using Javascript to construct objects using multiple iterations

I am seeking clarification on how to handle mock data that includes multiple reviews for each product.

The review_id is incremented based on the primary key, while the product_id may have duplicate values due to multiple reviews being associated with the same product. Here's an example:

const data = [
  { review_id: 1, product_id: 1 },
  { review_id: 2, product_id: 1 },
  { review_id: 3, product_id: 2 },
  { review_id: 4, product_id: 2 },
  { review_id: 5, product_id: 3 },
  { review_id: 6, product_id: 3 },

 (...)

];

I attempted to generate objects in an array using a nested loop:

const reviewLength = 10;
const productLength = 2;

const mappedReview = [];
for (let i = 1; i <= reviewLength; i++) {
  for (let j = 1; j <= productLength; j++) {
    const review_id = i * j;
    const product_id = j;

    mappedReview[i * j - 1] = {
      review_id,
      product_id
    };
  }
}

console.log(mappedReview);

However, instead of generating objects, the console output was:

[ { review_id: 1, product_id: 1 },
  { review_id: 2, product_id: 1 },
  { review_id: 3, product_id: 1 },
  { review_id: 4, product_id: 1 },
  { review_id: 5, product_id: 1 },
  { review_id: 6, product_id: 1 },
  { review_id: 7, product_id: 1 },
  { review_id: 8, product_id: 1 },
  { review_id: 9, product_id: 1 },
  { review_id: 10, product_id: 1 },
  <1 empty item>,
  { review_id: 12, product_id: 2 },
  <1 empty item>,
  { review_id: 14, product_id: 2 },
  <1 empty item>,
  { review_id: 16, product_id: 2 },
  <1 empty item>,
  { review_id: 18, product_id: 2 },
  <1 empty item>,
  { review_id: 20, product_id: 2 } ]

It appears that the loops were executed correctly, but the presence of <1 empty item> suggests null values in the output.

Answer №1

If you want to ensure that your product_id increases for every productLength entries in the mapped review, you can achieve this using a single loop:

const reviewLength = 10;
const productLength = 2;

const mappedReview = [];
let product_id = 1;
let product_counter = 1; // Keeps track of when to increment product_id
for (let review_id = 1; review_id <= reviewLength; review_id++) {
    // Add object with review_id and product_id
    mappedReview.push({review_id, product_id});
    // Increment product_id if needed
    if (product_counter++ === productLength) {
        ++product_id;
        product_counter = 1;
    }
}

console.log(mappedReview);
.as-console-wrapper {
    max-height: 100% !important;
}

Alternatively, you can calculate product_id directly based on the review_id value:

const reviewLength = 10;
const productLength = 2;

const mappedReview = [];
for (let review_id = 1; review_id <= reviewLength; review_id++) {
    // Add object with review_id and calculated product_id
    mappedReview.push({
        review_id,
        product_id: Math.ceil(review_id / productLength)
     });
}

console.log(mappedReview);
.as-console-wrapper {
    max-height: 100% !important;
}


In a comment, you inquired about using array methods like map or reduce:

Can I use the array methods map,reduce, etc. to express this case?

You could potentially use a combination of array methods like map by creating an array first, filling it, and then mapping over it. However, utilizing the mapping callback feature of Array.from seems more appropriate:

const reviewLength = 10;
const productLength = 2;

const mappedReview = Array.from({length: reviewLength}, (_, index) => ({
    review_id: index + 1,
    product_id: Math.ceil((index + 1) / productLength)
}));

console.log(mappedReview);
.as-console-wrapper {
    max-height: 100% !important;
}

To incorporate a map function, you could do something like

Array.from({length: reviewLength},
followed by (Array(reviewLength).fill().map(:

const mappedReview = Array(reviewLength).fill(0).map((_, index) => ({
    // ...
}));

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

Sending a `refresh` to a Context

I'm struggling to pass a refetch function from a useQuery() hook into a context in order to call it within the context. I've been facing issues with type mismatches, and sometimes the app crashes with an error saying that refetch() is not a funct ...

Unable to transmit information using Postman for registration API

I have been struggling to send data via a POST request to the register API, but for some reason, the data is not being transmitted. I have tried adjusting the settings on Postman, tinkering with validation rules, and various other troubleshooting steps, ye ...

I am in search of a clean and efficient method to modify the class of a link that triggers an HTMX request in Django. Perhaps something like "auto-refresh" or a similar solution would be ideal

I've encountered an issue with HTMX in Django. The page consists of two main components: a list of categories and the content that is displayed when a category is clicked. Initially, everything was working smoothly with standard htmx functionality. H ...

Why won't my AngularJS Google Maps marker trigger any events?

My issue is with the marker event not working on a UI Google Map. I am using this link. Here is my view setup: <ui-gmap-markers models="mapResult" fit="true" idkey="mapResult.id" coords="'form_geo'" click="'onclick'" events="mapRe ...

Troubleshooting problem with Materialize CSS in UI router

Incorporating Materialize CSS along with Angular's ui.router for state management and HTML rendering has led to a challenge. Specifically, the Materialize Select component is not initialized upon state changes since Materialize components are typicall ...

When tapping on grid items in the Safari browser using React Material-UI, they mysteriously switch positions

I've encountered an issue with grid Items in my React MATERIAL-UI project, specifically in the Safari browser. The problem does not occur in Chrome or Firefox. Within the grid, there are checkboxes that move from one place to another when clicked, a ...

"Troubleshooting: Issue with Material-UI TextField not

Currently working with version "@material-ui/core": "^4.2.1" of material-ui. The following code snippet is not matching the examples provided on the website: <div> <TextField id="outlined-search" label="Search field" type="search" variant="ou ...

Deciphering the method to retain added text

Imagine you have this code snippet: $('.button').click(function() { $('body').append("<p>Random Text</p>"); }); Whenever the .button is clicked, text is added to the body. How can we make sure that this text is saved a ...

Exploring Commitments in React

I'm currently navigating the world of promises and finding it challenging to grasp! My main focus right now is setting up an authentication system for my application. RegisterPage The handleSubmit function in my RegisterPage looks like this: handl ...

Implementing Material-UI Autocomplete: How to Include a Starting Value for the startAdornment

I am using autocomplete with multiple selection permission. https://codesandbox.io/s/bold-jackson-dkjmb?file=/src/App.js In the provided example, there are 3 options for cities. How can I manually insert a value in TextField that is automatically selected ...

The challenge with handling matrix arrays in Javascript

In my simplified drag and drop shopping cart project using jqueryui, I am encountering an issue with adding data (id, name, price) to an array. Despite trying various methods to add the data array to the main container, I consistently encounter the error ...

Best JavaScript approach for discovering time-dependent occurrences

In my Javascript code, I am working with an array of objects that have event start and end times stored as milliseconds. The current search algorithm in our codebase loops through the array until finding an event that contains a specific moment: // Lookin ...

Show HTML form elements on the page using jQuery or JavaScript

Is there a jQuery or JS library that can perform the following task: If the user inputs 'x' in A01, then make A01_1 visible. Otherwise, do nothing. <form id="survey"> <fieldset> <label for="A01">A01</label&g ...

The sorting process fails to make any changes, thus leaving the state unaffected

Is there a way to sort an array of objects in descending order by their id? No errors appear in the console. Even after calling the sort method, the state of allPosts remains unchanged. import { useState } from "react"; import Button f ...

Error message: Discord bot written in JS is unable to read the property 'execute' as it is undefined

I'm having trouble getting this code to work. Here is the main file snippet: const fs = require('fs'); bot.commands = new Discord.Collection(); const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith ...

React component state change in reverse

As I work on a simple login form component, I encountered an issue where clicking on the form should make it disappear and only display my JSON data. However, due to my limited experience with React state management, I seem to be achieving the opposite eff ...

Can someone help me identify the issue with my JavaScript code?

Recently, I attempted to transfer data from JavaScript to HTML using Angular. Here is the code snippet: phonecatControllers.controller('start', ['$scope', function($scope){ $scope.lloadd=true; console.log('data - '+$ ...

Caution: It is important for every child within a list to possess a distinct "key" prop. What is the solution to this issue?

Lately, I've encountered an issue with my project. Previously, everything was working fine, but now I keep receiving an error that prevents my notes from showing up when I click on the "my notes" section. The backend is operational and I can see the s ...

What is the best way to verify if all the elements in an array of strings are present within the array?

I am working with two arrays of strings, array1 and array2, that I need to compare. I want to find a way to check if all elements from array2 are present in the elements of array1, and then create a new array based on this comparison. I believe using filte ...

Is it possible for the await block to be located outside of the async function that contains it?

setInterval(() => { // perform certain actions }, 1000) const bar = async () => { const response = await api_request(); do_actions(); } await bar(); When the foo function is set to run, will it interfere with the execution of the setInterval ...