Variable not accessible in a Typescript forEach loop

I am facing an issue with a foreach loop in my code. I have a new temp array created within the loop, followed by a nested foreach loop. However, when trying to access the temp array inside the nested loop, I encounter a "variable not available" error.

let final = {
    array: []
};

myArray.forEach(item =>
{
    let newObject = { items: [] };

    item.subArray.forEach(subItem =>
    {
        var subObject = { prop: subItem.prop };

        // Error here: "newObject is not available"
        newObject.items.push(subObject);
    });

    // Error here: "final is not available"
    final.array.push(newObject);
});

I understand that I could pass this as an argument to make the array accessible (eg:

item.subArray.forEach(subItem => {},
this);)

However, this solution doesn't work for me since tempArray is not defined at the class level.

I encounter the same problem when attempting to assign my temp array to the "final" array declared outside the foreach loop.

Is there a way to access the parent scope from within the foreach loop?

It's worth mentioning that this code is part of a function within a class. My goal is to aggregate properties with a specific value from within the subarray.

Screenshot demonstrating the issue: https://i.stack.imgur.com/hawoz.png
(The code visible in the image is within the first forEach loop)


Update: I managed to resolve this issue by addressing the use of let and var. Refer to my answer below for more information.

Answer №1

The code snippet you posted in the question cannot be your actual code. If it were, you wouldn't have encountered issues accessing finalArray.

Both snippets yield very distinct results.

The first one will provide an array of all the properties within the subitems of the last item.

The second one will generate an array of arrays, with each inner array containing the properties of the subitem.

If I grasp your intention correctly, you aim to obtain a single array encompassing all the properties from the subitems. Essentially, you want to map each item to an array of subitem properties and then flatten the outcome into a unified array.

How about this approach?

var items = [
    {subitems:[
        {prop:1},
        {prop:2},
    ]},
        {subitems:[
        {prop:3},
        {prop:4},
    ]},
]

var result = items.map(function(item){
    return item.subitems.map(function(subitem){
        return subitem.prop;
    })
}).reduce(function(prev,curr){
    return prev.concat(curr);
},[]);

console.log(result);

Answer №2

Update: After some troubleshooting, I finally managed to solve the issue at hand. It turns out that in my original code, I had used TypeScript's let keyword to create newObject. Switching it to var resolved the problem.

This experience highlighted a gap in my knowledge regarding the distinction between let (block scope) and var (global scope) - live and learn!

While the solution provided below also worked for me, the simple act of changing let to var made my initial code function flawlessly.


To address the issue, I opted to utilize map() instead of forEach():

var final = {
    array: []
};

var finalArray = myArray.map(function (item)
{
    let newObject = { items: [] };

    var tempArray = item.subArray.map(function (subItem)
    {
        var subObject = { prop: subItem.prop };
        return subObject;
    });

    newObject.items = tempArray;

    return newObject;
});

final.array = finalArray;

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

Can you set up a mechanism to receive notifications for changes in an array variable in Angular?

I'm exploring methods to delay an HTTP request until the user stops interacting. I am considering using the debounceTime() operator from RxJs, but I need this to be triggered by changes in an array that I have defined. Here is the scenario: export c ...

What are the challenges associated with using replaceChild?

function getLatestVideos(url) { var http = new XMLHttpRequest(); http.open("GET", url, false); // false for synchronous request http.send(null); return http.responseText; } var videosText = getLatestVideos("https://www.googleapis.com/youtube/v3/se ...

Breaking down and modifying JavaScript JSON objects

Can someone explain how to separate a JSON object and make updates based on the ID? I've heard about using stringify! But how do I actually implement the function to update the object? <input type="text" value="{"id":"1","price":"30.00","edit":0}, ...

Having trouble with Nextjs API Integration - encountering error 404

I'm currently facing a major issue and I've hit a dead end. I've been spending days trying to connect my local nextjs 14 app to the CVENT API, but I keep receiving a persistent 404 error. Here's what is displayed in the frontend console ...

Mongoose search operation coming up with a blank array

Whenever I utilize $search in mongoose, it returns an empty array. Data Model const mongoose = require('mongoose'); const studentSchema = new mongoose.Schema({ name: { type: String }, }); studentSchema.index({ name: 'text' }); con ...

Having trouble concealing the logout button even after signing out with ng-show in angularjs

The code for displaying the logout button is as follows: <li class="dropdown" data-ng-if="userName"> <a href class="dropdown-toggle clear" data-toggle="dropdown" data-ng-show="userName"> </a> <!-- dropdown --> <u ...

What is the best way to manage div visibility and sorting based on selections made in a select box?

Explaining this might get a bit confusing, but I'll do my best. In my setup, I have two select boxes and multiple divs with two classes each. Here is what I am trying to achieve: When an option is selected, only the divs with that class should be ...

JavaScript hovering drop-down feature

Hi there, I'm just starting out with javascript and could use some help with a simple script. I have a shopping cart drop down that currently activates when clicked. However, I want it to fade in when hovered over instead. I've tried using .hove ...

Despite population, MongooseJS still renders blank array

Currently in the process of developing an application using Node.js with MongooseJS as the middleware for handling database operations. Encountering an issue with nested schemas, specifically with one of them being populated incorrectly. Despite tracking ...

Steps for integrating a Facebook Messenger chatbot with a MongoDB database in order to submit requests and retrieve responses through conversations with the bot

I am currently working on integrating my Facebook Messenger chatbot with a MongoDB database. The chatbot I have created is a simple questionnaire chatbot that takes text inputs and displays buttons with options. When a user clicks on a button, it should ...

The server is not allowing the requested method through HTTP POST and therefore returning

Excuse me if this question sounds beginner or if my terminology is incorrect, because I am new to this. I have created a basic Python API for reading and writing to a database (CSV file) with Angular 5 as my front end. While I was able to successfully ret ...

The browser is not displaying the HTML correctly for the Polymer Paper-Menu component

I attempted to implement a paper-menu, but I am facing issues with the rendered HTML and its interaction. When I click on a menu item, the entire list disappears due to the paper-item elements not being properly placed inside a key div within the paper-men ...

"Incorporating splice in a for loop is causing issues and not functioning

I've been attempting to remove an item from an array, but for some reason, it's not working. Here's the code I'm using: vm.Continue = function () { $scope.invalidList = []; if (vm.errorexsist === true) { var table = doc ...

Implementing restify on a website that mandates user login authentication

Currently, I am operating a REST API server using restify. In addition, my front-end consists of angularjs with html, css, and js files hosted on an Apache webserver. The next step is to implement user login authentication for this webapp. Access to the w ...

Convenient way for users to easily choose an icon from a vast selection of icons

I am currently working on a web application that allows users to create new categories. These categories are then inserted into a database using form post. Each category should have an icon associated with it, and I want users to be able to select the ico ...

Comparing dates in Angular 6 can be done by using a simple

Just starting with angular 6, I have a task of comparing two date inputs and finding the greatest one. input 1 : 2018-12-29T00:00:00 input 2 : Mon Dec 31 2018 00:00:00 GMT+0530 (India Standard Time) The input 1 is retrieved from MSSQL database and the in ...

Once it hits the fourth tab, it must not cycle back to the first one

Hi there, I'm new to JavaScript I noticed that when I click the left and right arrows, the tabs circle back to the beginning However, I would like the circle to stop. When it reaches the fourth tab, it should not go back to the first. This should also ...

Combining Two Dropdown Selections to Create a Unique Name using Angular

I am facing a challenge with 2 dropdown values and input fields, where I want to combine the selected values from the dropdowns into the input field. Below is the HTML code snippet: <div class="form-group"> <label>{{l("RoomType")}}</labe ...

Unity3D: Troubleshooting a Code Issue

Encountering an issue with my code and struggling to find a solution. I've tried moving my c# script up to the standard assets folder as suggested in my research but it didn't resolve the problem. Any assistance would be greatly appreciated! Than ...

What is the best method to reset the chosen option in a dynamic select dropdown using React?

I have a form set up with a Select dropdown that is populated dynamically from the server. The issue I'm facing is that after selecting an option from the dropdown and then saving or canceling the form, the selected value remains in the field when I ...