In the world of JavaScript, encountering a nested forEach loop may lead

Encountering a typeError while attempting to reconstruct another object using double forEach:

const users = [
    {teacher: [
        {file: 'chemistry', size: '2MB'},
        {file: 'math', size: '1MB'}]
    }, {student: [
        {file: 'chemistry', size: '3MB'},
        {file: 'math', size: '4MB'}]
    }
];

let final = {};

users.forEach(function(i) {

    i.forEach(function(j){
        let filesizestring = 'newfilesize'+j.size;
        final[j] = j;
        final.j[j.file] = filesizestring;
    })
})

Desired output:

{teacher: {
        chemistry: 'newfilesize2MB',
        math: 'newfilesize1MB'
    }, 
student: {
        chemistry: 'newfilesize3MB',
        math: 'newfilesize4MB'
    }
}

Any suggestions for fixing this issue?

update

If nested forEach is not feasible, how can I achieve the same result?

Answer №1

When running a loop over i -> i.forEach(function(j), remember that i is an object. To iterate through the key-value pairs of the object, use for (key in i). For each key, access the array by using i[key].

const users = [{
  teacher: [{
      file: 'chemistry',
      size: '2MB'
    },
    {
      file: 'math',
      size: '1MB'
    }
  ]
}, {
  student: [{
      file: 'chemistry',
      size: '3MB'
    },
    {
      file: 'math',
      size: '4MB'
    }
  ]
}];

let finalResult = {};

users.forEach(function(item) {
  for (key in item) {
    var obj = {};
    item[key].forEach(function(element) {
      let fileSizeString = 'newfilesize' + element.size;
      obj[element.file] = fileSizeString;
    });
    finalResult[key] = obj;
  }
});

console.log(finalResult);

I hope this explanation helps!

Answer №2

To achieve this, you can utilize the reduce method as shown below:

const usersList = [{
    teacher: [{
            subject: 'chemistry',
            fileSize: '2MB'
        },
        {
            subject: 'math',
            fileSize: '1MB'
        }
    ]
}, {
    student: [{
            subject: 'chemistry',
            fileSize: '3MB'
        },
        {
            subject: 'math',
            fileSize: '4MB'
        }
    ]
}];

let processedData = usersList.reduce((accumulator, user) => (key = Object.keys(user)[0], { ...accumulator,
    [key]: user[key].reduce((acc, subjectDetails) => ({ ...acc,
        [subjectDetails.file]: 'newfilesize' + subjectDetails.size
    }), {})
}), {})

console.log(processedData)

Answer №3

i is not an array object in the forEach loop, so you cannot call forEach on an object. Instead, you can extract the array from the object and then apply the forEach method on that array.

const users = [
        {teacher: [{ file: 'chemistry', size: '2MB' },{ file: 'math', size: '1MB' }]}, 
        {student: [{ file: 'chemistry', size: '3MB' },{ file: 'math', size: '4MB' }]}
];

let final = {};

users.forEach(function (user) {
    let key = Object.keys(user)[0];
    let obj = {};
    user[key].forEach(function(file){
        obj[file.file] = 'newfilesize' + file.size;
    });

    final[key] = obj;
});

console.log(final);

Answer №4

I simply cannot tolerate not having a function, even if it's named strangely.
The main issue here is similar to what other answers have touched on: your top-level variable users is an array with a forEach method. However, this array contains objects that do not have a forEach method. Instead, you can use for in for iteration (link intended) to access teacher/student data. Furthermore, the last level is once again an array, which can be iterated using forEach.
Therefore, there is indeed a nested forEach, but it is nested within a for in.

const users = [
    {teacher: [
        {file: 'chemistry', size: '2MB'},
        {file: 'math', size: '1MB'}]
    },
    {student: [
        {file: 'chemistry', size: '3MB'},
        {file: 'math', size: '4MB'}]
    }
];

function magic(coll){
  var res={};
  coll.forEach(function(user){
    for(misc in user){
      user[misc].forEach(function(subject){
        this[subject.file]="newfilesize"+subject.size;
      },res[misc]={});
    }
  });
  return res;
}

console.log(magic(users));

(If someone has a better word than misc, please suggest)

Answer №5

Have you considered using a data structure similar to this instead?

const users = [
    {type: "teacher",
     files: [
        {file: 'chemistry', size: '2MB'},
        {file: 'math', size: '1MB'}]
    }, {type: "student",
        files: [
        {file: 'chemistry', size: '3MB'},
        {file: 'math', size: '4MB'}]
    }
];

let final = {};

users.forEach(function(i) {

    i.files.forEach(function(j){
        let filesizestring = 'newfilesize'+j.size;
        final[j] = j;
        final[j][j.file] = filesizestring;  // <-- Can you explain this line?
    })
})

I'm curious about the commented line, could you offer some insight into its purpose?

Answer №6

Converting an array into an object without verifying the number of items can be risky. The approach taken in this response accounts for multiple items and returns an array with the desired structure. If you are certain there will only be one item, you can simply use final[0] as the resulting array will also contain a single element.

const users = [{
  teacher: [{
    file: 'chemistry',
    size: '2MB'
  }, {
    file: 'math',
    size: '1MB'
  }]
}, {
  student: [{
    file: 'chemistry',
    size: '3MB'
  }, {
    file: 'math',
    size: '4MB'
  }]
}];

final = [];
users.forEach(item => {
  let obj = {};
  let userType = item.teacher ? "teacher" : "student";
  obj[userType] = {};
  item[userType].forEach(subItem => obj[userType][subItem.file] = 'newfilesize' + subItem.size);
  final.push(obj);
});

console.log(final);

Answer №7

In order to improve the efficiency of your data, I suggest restructuring it as follows:

const usersData = [
  {
    role:"teacher",
    documents: [
      {name: 'chemistry', fileSize: '2MB'},
      {name: 'math', fileSize: '1MB'}
    ]
  }, {
    role:"student",
    documents: [
      {name: 'chemistry', fileSize: '3MB'},
      {name: 'math', fileSize: '4MB'}
    ]
  }
];

This new structure allows for easier access and manipulation of user roles and their respective documents:

for(const userData of usersData){
  for(const document of userData.documents){
    document.fileSize = "newFileSizeValue" + document.fileSize;
  }
}

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

Iterate over a JSON object to calculate the total sum of values based on distinct nested properties

Here is a JSON object that contains cost and author information. I am working on this in Express.js and using Underscore. [ { "Cost": 250, "author": { "id": "2", "name": "Joe", "workId": "5" } }, { ...

Occasionally, the system may mistakenly flag a password as invalid even though it is indeed correct

To ensure the password meets certain criteria, it must start with a Z, have at least 8 characters, and contain an asterisk *. Take a look at this validating function: function validatePassword() { var strPassword; //Prompt user to enter pas ...

When a function is passed as an argument in Javascript code, the setTimeout function may behave in unique ways

After running the code below, I noticed an interesting behavior: setTimeout(() => console.log('first'), 0) console.log('second'); As expected in JavaScript's asynchronous nature, the output was as follows: second first Howev ...

Loading the JS file after waiting on Lib (IronRouter) causes the HTML not to load properly

Currently, I am utilizing wait-on-lib along with IRLibLoader.load() in conjunction with Iron-Router, following the instructions provided in the tutorial found at: . My objective is to load external javascript code. Below is a snippet of my routing code: R ...

Navigating Highcharts within jQuery

I am looking to integrate some new data into an existing Highchart on the page using the following code snippet: window['chart_' + skill_id].series[0].addPoint(data, true, false); This method works perfectly if I originally created the chart li ...

The program encountered an error: Unable to access the 'toDate' property of an undefined value

Encountering an error in my Firebase project while running a Firebase function. The specific error message is: Cannot read property 'toDate' of undefined, related to converting admin.firestore.Timestamp to Date format. Any suggestions on how to ...

Dispatching actions to update the Redux state is not reflecting any changes

Currently, I am developing a feedback board website and implementing a roadmap route where users can track website improvements. On mobile, I want to incorporate a three-section slide feature: planned, in-progress, and live stages. I found a useful code sn ...

Parsing JSON sub-objects with individual names autonomously

I am currently exploring the capabilities of the VirusTotal API in order to develop a script that can scan and provide detailed reports. The challenge I am facing revolves around the SCANS section of my code where I am struggling to extract and display eac ...

Error in React Material UI: 'theme' variable is not defined - no-undef

In the process of developing a basic React application with material-ui, I am incorporating MuiThemeProvider and ThemeProvider for themes. App.js import React from 'react'; import { createMuiTheme, MuiThemeProvider } from '@material-ui/co ...

What is the best method for preventing a specific .CSS file from being included in the output when using

foo.js foo.css bar.css foo.js contains foo.css. Also, foo.css includes bar.css. After bundling, I end up with bar.css which I want to exclude. I am using MiniCssExtractPlugin to separate css and js files. Methods I have attempted: IgnorePlugin. It s ...

Integrate new HTML elements into the React component structure

Is there a way to seamlessly add a DOM element using vanilla javascript into a hierarchy of DOM nodes generated by React without it being removed when the state updates? Motivation: I am working on a browser extension and aiming to closely integrate with ...

Using angular.copy function to copy an array with a custom property

Let's use the example below to illustrate an issue: var ar = [4, 2, 3]; ar.$x = 'something'; var br = angular.copy(ar); console.dir(br); After copying ar to br, the $x property is no longer present. This is because when Angular copies an a ...

How can JavaScript mimic type-specific extension methods?

Imagine you have a class named Person. Its structure is as follows: function Person(name, age) { this.name = name; this.age = age; } Now, suppose you have an array of Persons (or individuals) and you wish to identify the oldest one. In C#, you ca ...

Fixed Array of String in Kotlin

Can a fixed-size array of strings be created in Kotlin, similar to Java? For example, something like val arrayOfString: Array(5) ...

Retrieve Django imagefield file name using jQuery before submitting

Exploring the essential Django image file upload procedure, where the image model incorporates the ImageField class. There's a custom display button replacing the default upload button which usually showcases the image name alongside it. Hence, the ne ...

Tips for using jest toHaveBeenCalled with multiple instances

Currently, I am in the process of writing a test case for one of my functions. This function calls another function from a library, and I am attempting to mock this function (saveCall). Below is a snippet of the sample code in question: import { Call } fro ...

Should all pages in React be rendered on the server side?

Currently, I rely on Next.js for implementing server-side rendering on my React website. At the moment, I have implemented server-side rendering across almost all pages of the site, including profile information and other content that requires a login to ...

What is the best way to retrieve nested ng-include scope/fields within a form?

I've searched high and low but haven't found a solution to my unique issue. Just like many others, I'm facing the challenge of ng-include creating a new child scope that doesn't propagate to the parent. I have a versatile template tha ...

Encountered a CPU-side conversion issue causes Browser to crash when attempting to load an object using threejs

After implementing the code from the threejs example/loader/obj/mtl to load an object exported via Unity3d, some customers have reported browser crashes on their machines. A screenshot of the error message in a browser console can be viewed here. Addition ...

Making sure to consistently utilize the service API each time the form control is reset within Angular 4

In the component below, an external API service is called within the ngOnInit function to retrieve an array of gifs stored in this.items. The issue arises when the applyGif function is triggered by a user clicking on an image. This function resets the For ...