Create copies of a single array containing objects in various new arrays

I need to create duplicates of an array of objects multiple times, as I require each one for different uses.

if(!this.tempLookups){
    for (let count = 0; count < this.dates.length; count++) {
       this.tempLookups[count] = this.lookups[key];
    }
}

An error occurred: Uncaught (in promise) TypeError: Cannot set property '0' of null

Answer №1

The main cause of the error lies within the error message indicating an attempt to set a property for a null value. To resolve this, it is recommended to define the property after the if statement.

if(!this.tempLookups){
    his.tempLookups = [];
    for (let count = 0; count < this.dates.length; count++) {
       this.tempLookups[count] = this.lookups[key];
    }
}

To achieve the same result in a more concise manner without using a for loop, you can utilize the Array#fill method since you are filling with identical values.

if(!this.tempLookups){    
   this.tempLookups = new Array(this.dates.length).fill(this.lookups[key]);
} 

Answer №2

To achieve this, follow these steps:

if (!this.tempLookups) {
    this.tempLookups = [];
    for (let i = 0; i < this.dates.length; i++) {
       this.tempLookups.push(Array.from(this.lookups[key]));
    }
}

It is important to note that the this.tempLookups variable is set as an empty array at the beginning to avoid any conflicts when inserting data. Using the Array.from method within the for loop ensures that each iteration creates a shallow copy of the this.lookups[key] array. This prevents changes made to one array from affecting all others, as they are separate arrays and not just references to the same array.

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

A step-by-step guide on accessing and displaying local Storage JSON data in the index.html file of an Angular project, showcasing it on the

I am facing an issue with reading JSON data from localStorage in my Angular index.html file and displaying it when viewing the page source. Below is the code I have attempted: Please note that when checking the View page source, only plain HTML is being ...

Images copied using Gulp are often distorted or incomplete

There is a simple task of moving an image from one folder to another. gulp.task('default', function () { return gulp.src('./img/*.*') .pipe(gulp.dest('./image')); }); Previously, everything was running smoothly, b ...

``Change the color of the sections in a 3D pie chart on a Highcharts

I am looking to create a custom pie chart with two different colors: one for the main surface and another for the sides. Currently, I can only configure the lighter blue color for the main surface, but I would like to also change the darker blue color for ...

Steps for creating a CodeBlock in a Next.js Website blog similar to the one in the provided image

Learn how to insert a code block in Next.js. def greet(name): """ This function greets the person passed in as a parameter. """ print("Hello, " + name + ". Good morning!") Here is an example of ...

Is there a way to confirm the presence of multiple attributes in a JSON format using JavaScript?

Currently, I am developing a module that processes multiple complex JSON files and requires a method to notify users if certain elements are missing. Although the current approach works, I can't shake the feeling that there must be a more efficient a ...

Will the .replaceWith() method alter the code visible to search engines?

After successfully modifying the content of specific H1 elements to not return the value from a global variable using the following code; <script type="text/javascript"> $(document).ready(function() { $("H1").filter(function() { return $(this).text ...

Include a novel item into the JSON string that is being received

Recently, I attempted to parse an incoming JSON string and insert a new object into it. The method I used looked like this: addSetting(category) { console.log(category.value); //Console.log = [{"meta":"","value":""}] category.value = JSON.parse(c ...

programming / mathematics - incorrect circular item rotation

I need help arranging a sequence of planes in a circular formation, all facing toward the center. However, I seem to be experiencing issues with the rotation after crossing the 180-degree mark. While my objects are correctly positioned around the circle, t ...

uWebSockets supporting multiple concurrent user sessions

To keep things simple, let's assume that my server is running just one uWebSockets instance: struct UserData { uWS::WebSocket<true, uWS::SERVER> *ws; bool logged_in = false; ID user_id; }; uWS::SSLApp() .ws<UserData>( ...

When calling a method that has been created within a loop, it will always execute the last method of the

In my project, I am utilizing node version 0.8.8 in conjunction with express version 3.0. Within the codebase, there exists an object named checks, which contains various methods. Additionally, there is an empty object called middleware that needs to be p ...

MacGyver's innovative Angular mac-autocomplete directive fails to properly auto-complete

I have incorporated the .css and .js files for MacGyver in my HTML document. Additionally, I have added 'Mac' as a dependency in my Angular application. The following code snippet is included in my HTML: <mac-autocomplete ng-model="selected" ...

Is there a Page Views tracker in sinatra?

Help needed with implementing a page views counter using Sinatra and Ruby. I attempted using the @@ variables, but they keep resetting to zero every time the page is reloaded... Here's an example: Appreciate any advice! ...

What could be causing the presence of additional characters in the responseText received from the Servlet to JavaScript via Ajax?

I am currently involved in a project where I am attempting to retrieve the username from a session that was created using the code below: GetCurrentUserInfo.java package servlet; import java.io.IOException; import java.io.ObjectOutputStream; import java ...

What could be causing my slideshow to loop continuously when I click the next button, but not when I click the previous button

I managed to successfully code buttons that control an auto-advancing slideshow. While both buttons are functional, only the next button is able to cycle through all images. However, when using the previous button to navigate back to the beginning, the who ...

Continuously performing a task in Node.js every 2 minutes until a JSON file, which is being monitored for changes every few seconds

In order to modify a process while my program is running, I need to manually change a value in a .json object from 0 to 1. Now, I want the program to: periodically check the .json file for changes. refresh a browser page (using puppeteer) every 2 minutes ...

Having difficulty attaching events to Bootstrap 3 button radios in button.js

Struggling with extracting the correct value from a segmented control created using the radio button component of button.js in Twitter Bootstrap 3. Upon binding a click event to the segmented control and running $.serialize() on its parent form, I noticed ...

Developing a single page that caters to various users' needs

Greetings to all my friends, As a front end developer, I am in the process of implementing a dashboard for a project that involves different users with varying permissions. Each user should only have access to certain parts of the page, resulting in some ...

Issues with Pageinit and Ready Event Timings

Check out this fiddle where I am experiencing an issue related to pageinit and ready events In the fiddle, everything functions properly using onLoad and onDOMready. This includes: The subject listings are loaded correctly with a popup displaying module ...

My goal is to display the products on the dashboard that have a quantity lower than 10. This information is linked to Firestore. What steps can I take to enhance this functionality?

{details.map((val, colorMap, prodName) => { I find myself a bit perplexed by the conditional statement in this section if( colorMap < 10 ){ return ( <ul> <li key= ...

Data binding functions properly only when utilizing the syntax within the select ng-options

In the book AngularJS in Action, I came across this Angular controller: angular.module('Angello.Storyboard') .controller('StoryboardCtrl', function() { var storyboard = this; storyboard.currentStory = null; ...