Iterating through each loop and storing the values in an array

After researching various topics related to the issue, I found that the solutions provided are not working for me. It seems like there is a logic problem in my code. It's quite simple - I have two arrays (one containing three strings and the other containing three dates).

My goal is to create an object that pairs the first string from the first array with the first date from the second array.

The issue I'm facing is that the function theMainFunc() is creating three objects with the last index of each array, instead of matching them as intended.

Below is the code snippet:

var dlcNameList = ['they shall not pass', 'in the name of the tsar', 'apocalypse'];
var dlcReleaseDate = [new Date(2017,2,28), new Date(2017,6,15), new Date(2017,11,25)];

function objectCreator (dlcObject,dlcName,dlcDate) {
dlcObject.name = dlcName;
dlcObject.date = dlcDate;
return dlcObject;
}

function theMainFunc() {

var dlcDetails = {};
var i = 0;
var storage = [];
var x;

for (i; i <= 2; i++){
x = objectCreator(dlcDetails,dlcNameList[i],dlcReleaseDate[i]);
storage[i] = x;
}

return storage; //This returns an array with three "Same" objects. Not what I want to really acheive
}

console.log(theMainFunc())

Answer №1

Here's the solution for you!

Important: Instead of creating a new object with each iteration, you can utilize Array#forEach to easily push an object with pre-defined properties and keys into the result array.

var dlcNameList = ['they shall not pass', 'in the name of the tsar', 'apocalypse'],
    dlcReleaseDate = [new Date(2017,2,28), new Date(2017,6,15), new Date(2017,11,25)],
    result = [];
    
    dlcNameList.forEach((v,i) => result.push({name : v, date : dlcReleaseDate[i]}));
    console.log(result);

Answer №2

Due to the declaration of dlcDetails above the loop, there is a mistake occurring where you are unintentionally reusing it and updating its values instead of pushing a new object to the array.

It's important to note that when you pass an object/array to a function or set it as the value of another object's property, you are not creating a copy of that object, but rather sharing it. This means any modifications made to the object will be reflected in the original. This concept is sometimes erroneously referred to as "pass by reference."

function theMainFunc() {
    var storage = [];

    for (var i = 0; i <= 2; i++){
        var dlcDetails = {};

        var x = objectCreator(dlcDetails,dlcNameList[i],dlcReleaseDate[i]);
        storage[i] = x;
     }

     return storage;
}

Answer №3

Your code has an issue where you are passing the same object to the objectCreator() function three times. This results in the storage having three references to the same object, with properties being overridden each time the function is called. To fix this, you should create a new object inside the objectCreator() function instead of passing it as a parameter.

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

Encountered an error during the production build of NEXTJS, where it panicked due to the global thread pool not being initialized

While hosting my app on Heroku and running git push heroku main, I encountered the following error: panicked at 'the global thread pool has not been initialized.: threadpool builderror { kind: ioerror(error { kind: unsupported, message: "operatio ...

Is there a way to utilize jQuery for parsing the XML file?

When trying to parse the file, the value for "name" in the code is always an empty string. Here is my XML data: <row> <id>1</id> <AnrufenZahl>64</AnrufenZahl> <NameOperator>Ioan</NameOperator> </row> ...

retrieve the parent frame's request URL

I am faced with the task of writing a JSP code that retrieves the getRequestURL() of the parent frame (the URL shown in the address bar) from a child frame. However, when I attempt to do this, I only obtain the URL of the child frame. Is there anyone who ...

Having issues with adding elements to an array object in JavaScript

I've got some HTML code that looks like this: HTML: <INPUT TYPE=CHECKBOX NAME="clcik" onClick="add('1234','blah')" /> <input type="hidden" id="project" value="" /> JS: function add(obj1 , obj2){ var jsonAr ...

Sorting columns using custom conditions in DataTables

Within a PHP project I am working on, I have encountered a need to organize a specific column using a custom condition or order rather than relying on the default ordering provided by DataTable (ascending or descending). The project involves four distinct ...

Discontinuing the fieldset tab interface feature from a Dexterity content type

I am looking to modify a condition to prevent the loading of certain javascript code when inserting an object of my content type. The current condition works only when editing the object: <?xml version="1.0"?> <object name="portal_javascripts"> ...

Double submission issue with Angular form (multiple ajax requests)

My controller seems to be causing a form submission issue in AngularJS where the form is being submitted twice via a get request. Upon checking my database and the console network tab, I noticed that two submissions are logged, with the first submission sh ...

Adding new elements to an array does not activate the reactivity of Vue

After discovering that editing objects within an array doesn't function properly in vue.js due to its limitations, I tried using vue.set to resolve the issue, but it's proving to be quite challenging for me. Let's take a look at the sample ...

Generate with different HTML elements

This is a simple React code snippet: var Greetings = React.createClass({ render: function() { return <div>Greetings {this.props.name}</div>; } }); ReactDOM.render( <Greetings name="World" />, document.getElementB ...

Steps for initiating a $.ajax POST request from a client to a server

Currently, I am working on a phonegap application where I need to transfer some data from an HTML file to a server and receive a response in return. Everything works fine when all the files are on the same server. However, once I separate the files between ...

Having trouble retrieving information from the local API in React-Native

Currently, I have a web application built using React and an API developed in Laravel. Now, I am planning to create a mobile app that will also utilize the same API. However, I'm encountering an issue where I cannot fetch data due to receiving the err ...

Give drawn elements a touch of fuzziness and experiment with the color of the fragment shader

I am currently experimenting with creating an animated gradient effect by blending three separate blobs together in a melting-like fashion, with each blob moving independently. The desired result can be seen in the image provided below. So far, I have bee ...

Analyzing various field data collectively

Is there a way to use jQuery to compare multiple input field values and trigger an alert message saying 'There are similar values' if any match is found? <input value="111"> //similar <input value="222"> <input value="111"> //s ...

Execute jQuery after Angular has completed its loading process

I'm currently working on making some small adjustments to an existing website. This website was originally created using Angular. While my code is written with jQuery, I do have the flexibility to use any type of JavaScript necessary. Despite this, ...

JavaScript code to remove everything in a string after the last occurrence of a certain

I have been working on a JavaScript function to cut strings into 140 characters, ensuring that words are not broken in the process. Now, I also want the text to make more sense by checking for certain characters (like ., ,, :, ;) and if the string is bet ...

The function is invoked numerous times

My issue involves using jQuery to handle the mouseenter and mouseleave events. The problem arises when transitioning from one div to another, causing the events to trigger again. I am looking for a solution to only run these events once per mouse enter and ...

What is the reason behind Angular generating files with 'es5' and 'es2015' extensions instead of 'es6' (or no extension)?

Recently, I installed the Angular CLI (@angular/cli 9.0.1). My goal was to create a new Angular Element, package it, and then integrate it into another application. Following several blog tutorials, I found that they all mentioned the final step of creati ...

What is the best way to obtain the SearchIDs for various searchNames using JavaScript?

Who can assist me in resolving this issue? I am trying to retrieve the id of a searchName whenever a user selects the checkbox. Ideally, I would like to assign the value of the PHP line $search_row->searchid to the id attribute in the input field. Apolo ...

Encountering issues with React Apollo hooks after integrating React Native into the monorepo system

I am in the process of setting up a React web app and a React-native app within a monorepo using yarn workspaces. The web and controllers are functioning properly, allowing me to successfully execute graphql queries to my apollo-express server. However, up ...

What could be causing this code to malfunction when using D3.min version instead?

In this coding example, a scale and an axis object can be seen in the console: <!DOCTYPE html> <head> </head> <body> <script src="//d3js.org/d3.v5.js"></script> <script> console.log(d3.scale ...