During the final iteration, the Array forEach method is replacing the value of an object

Currently, I am iterating through an array of file names, breaking down the names, and saving the information in an object. For testing purposes, there are two file names that are almost identical except for the week "number" which should represent different weeks. However, I encountered a problem where the first entry is getting overwritten by the last iteration, resulting in only one entry for week 2.

This is the code snippet:

const planList = [
    'military_greekHero_achilles_week_1.htm',
    'military_greekHero_achilles_week_2.htm'
];

var _completePlan = {};

planList.forEach(_plan => {

// Extract data from the file name format: target_series_title_overview/week_weekNum.htm
    let _planPieces = _plan.split('.')[0].split('_'), // Remove the .htm
        _planTarget = _planPieces[0],
        _planSeries = _planPieces[1],
        _planTitle = _planPieces[2],
        _planOverview = _planPieces[3],
        _planWeek = _planPieces[4];

    _planOverview = _planOverview == 'overview' ? true : false;
    
// Start Building Plan Object
    _completePlan[_planTitle] = {
        info: {},
        weeks: {}
    }

// While iterating, _planWeek logs 1 and 2 but the entry for .weeks.1 gets replaced with .weeks.2
    _completePlan[_planTitle].weeks[_planWeek] = {
        sn: { inactive: true },
        mo: { inactive: true },
        tu: { inactive: true },
        we: { inactive: true },
        th: { inactive: true },
        fr: { inactive: true },
        st: { inactive: true }
    }
});

console.log(_completePlan);
});

I believe there might be a simple solution that I'm missing... any suggestions?

Answer №1

Before creating the object, it is important to check if it already exists to avoid overwriting the previous one:

if (!_completePlan.hasOwnProperty(_planTitle)) {
    _completePlan[_planTitle] = {
      info: {},
      weeks: {}
    }
  }

In addition, a restructuring statement has been included to streamline the code:

let [_planTarget, _planSeries, _planTitle, _planO, _planWeek] = _plan.split('.')[0].split('_'), // Remove the .htm
_planOverview = _planO === 'overview' ? true : false;

const planList = [
  'military_greekHero_achilles_week_1.htm',
  'military_greekHero_achilles_week_2.htm'
];

var _completePlan = {};

planList.forEach(_plan => {

  // Extracting data from the file name format: target_series_title_overview/week_weekNum.htm
  let [_planTarget, _planSeries, _planTitle, _planO, _planWeek] = _plan.split('.')[0].split('_'), // Remove the .htm
    _planOverview = _planO === 'overview' ? true : false;

  // Begin Building Plan Object
  if (!_completePlan.hasOwnProperty(_planTitle)) {
    _completePlan[_planTitle] = {
      info: {}, weeks: {}
    }
  }

  _completePlan[_planTitle].weeks[_planWeek] = {
    sn: { inactive: true},
    mo: { inactive: true},
    tu: { inactive: true},
    we: { inactive: true},
    th: { inactive: true},
    fr: { inactive: true},
    st: { inactive: true}
  }
});

console.log(_completePlan);

Answer №2

In each iteration, you are resetting the entirety of _completePlan[_planTitle]. This means that the objects 1 or 2 within the weeks object are not being "overridden," but rather their grandparent object is being set back to {info: {}, weeks: {}}.

To resolve this issue, you should check if the weeks object exists and only assign it to itself if it does; otherwise, assign it to an empty object.

Here's how you can achieve that:

const planList = [
    'military_greekHero_achilles_week_1.htm',
    'military_greekHero_achilles_week_2.htm'
];

var _completePlan = {};


planList.forEach(_plan => {

        // Extracting data from the file name format: target_series_title_overview/week_weekNum.htm
            let _planPieces = _plan.split('.')[0].split('_'),// Remove .htm
                _planTarget = _planPieces[0],
                _planSeries = _planPieces[1],
                _planTitle = _planPieces[2],
                _planOverview = _planPieces[3],
                _planWeek = _planPieces[4];

            _planOverview = _planOverview == 'overview' ? true : false;

            
        // Building Plan Object
            

        // While iterating, _planWeek logs 1 and 2, but the entry for .weeks.1 is replaced by .weeks.2
            _completePlan[_planTitle] = _completePlan[_planTitle] || {};
            _completePlan[_planTitle].info = _completePlan[_planTitle].info || {};
            _completePlan[_planTitle].weeks = _completePlan[_planTitle].weeks || {};


            _completePlan[_planTitle].weeks[_planWeek] = {
                sn: { inactive: true },
                mo: { inactive: true },
                tu: { inactive: true },
                we: { inactive: true },
                th: { inactive: true },
                fr: { inactive: true },
                st: { inactive: true }
    }
});
console.log(_completePlan);

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

The error message "The specified type '(key: String, value: Any)' does not contain any subscript members" is being displayed

I am currently navigating through an array of dictionaries using this particular code snippet. if let users = object["usersList"] as? [Any] { for user in users as! [String : Any] { print(user["id"]) } } Each dictionary in the array contai ...

Discover the steps to capture the ajax initiation and completion events

In my application, I have numerous ajax requests. To display a loading symbol while these requests are in progress, I am utilizing jquery ajaxStart and ajaxStop methods. However, for some reason, they seem to not be functioning as expected. Despite searc ...

Differences between Angular JS Objects and Arrays

I am having trouble creating an object with 3 properties inside. Each time I try to run the code, only the code expression is displayed. How do arrays and objects interact with each other? Here is my code snippet: var app = angular.module("FundAllocati ...

What causes addEventListener to not return a value?

In this snippet of code: let rockClick = rockBtn.addEventListener('click', playRound.bind("rock", computerPlay(), false)); After using console.log(), the output is undefined. The purpose of rockBtn:const rockBtn = document.querySelecto ...

Transform array into object in php - Transform the given array into an object using php

Can someone assist me in converting this array to an object in PHP? Below is the code I currently have: data: [ [ 1638849672000, 0.0025 ], [ 1638849732000, 0.0008 ], [ 1638849792000, 0 ...

Manipulate CSS Properties with Javascript Based on Dropdown Selection

I am currently working on implementing a feature that involves changing the CSS property visibility: of an <input> element using a JavaScript function triggered by user selection in a <select> dropdown. Here's what I have so far in my cod ...

Maintain the fancybox open even in case of ajax errors

I'm having an issue with my code where the fancybox closes automatically after displaying the error message briefly. I want it to remain open so that users have more time to fix their errors. What could be causing this problem? $(document).ready(func ...

Check an image preview prior to uploading through FileReader, rotates the image

After browsing through numerous posts about viewing images before uploading, I stumbled upon an intriguing solution that claimed to be simple using FileReader: function displayImage(input) { if (input.files && input.files[0]) { var reader = ne ...

Modify the hue of the div as soon as a button on a separate webpage is

Looking for assistance with a page called "diagnosticoST" that contains four buttons (btn-institucional, btn-economico, btn-social, btn-natural). These buttons have different background colors until the survey inside them is completed. Once the user comple ...

Using JavaScript to define an array of objects

My issue lies with transforming a JSON structure like the one below: [{ "groupid": 29, "percentage": 14 }, { "groupid": 29, "percentage": 22 }, { "groupid": 59, "percentage": 66, }] I am looking to convert it into the format shown ...

Looking to run a JavaScript command without the need for any triggering events?

Is there a way to execute the following JavaScript code without using any event and have it run at the start, onLoad of the page? function calculateDiscount() { var totalPrice = document.getElementsByClassName("Total")[0].innerHTML; var discountedPr ...

The Autocomplete feature from the @react-google-maps/api component seems to be malfunctioning as it returns

I'm encountering some difficulties with the Autocomplete component in @react-google-maps/api. While Autocomplete is working and displaying options, clicking on an option fills the input box but I'm only getting 'undefined' from the Plac ...

"The authentication cookie fields are not defined when trying to get the authentication in the Express framework

After setting up my React client on port 3000 and Express on port 5000, I encountered an issue. When logging in, the cookie fields are set without any problems. However, when trying to retrieve the isauth value, it shows as undefined. //login log message ...

What exactly does the 'app://' scheme entail when it comes to assets within Webpack-5-generated applications during development mode?

I've recently noticed a unique behavior in my Webpack 5-built application during development mode. The browser requests assets using a URL with an interesting app:// scheme. An example of this is: app:///node_modules/dir/to/package/index.js In the De ...

Adjusting the filter location in React-admin

This is the common method of implementing filters in react-admin https://i.stack.imgur.com/M8yq7.png However, in my particular scenario, I require the filters to be inside each column heading. For example: https://i.stack.imgur.com/GU2Pz.png The filter ...

Is it possible to conditionally call the Apollo Client in my Vue template script?

I have a scenario where I pass a query to the apollo client in my template file using a script tag. However, I want to find a more efficient way to handle this without having to specify the query every time. My idea is to pass a boolean value through a pro ...

Trigger the activation of an input field upon clicking an image labeled "edit"

I am currently developing a website where administrators have access to a dashboard page that displays a list of users. I am looking to implement a feature that allows admins to change the roles of other users directly from the same table row. Below is th ...

Tips for adding values to an array using an arrow function

Can someone assist me with pushing even numbers into an array using an arrow function? I'm unsure of how to do this. Here's my code: var arrayEvenNumbers = []; var evenNumbers = (arrayEvenNumbers) => { for (i = 2; i <= 20; i++) { i ...

Ways to apply Position Fixed to a particular Div element and subsequently eliminate that class while scrolling

Check out my current Jsfiddle project here I am working on a task that involves adding a class to a specific div when scrolling and then removing that class. Below is the JavaScript code I have written for this functionality: var targetDiv = $(".mainwra ...

Is it necessary to exclude the 'scripts' folder from your Aurelia project's .gitignore file?

Should I exclude the 'scripts' directory that Aurelia is building to in my CLI project from Git by adding it to .gitignore, or is there a specific purpose for tracking changes to this directory? ...