Array of objects encountering array problems

In the hierarchy, the admin should have access to test#1 & test#4, the manager should have access to test#2, and the head should have access to test#3. I attempted to implement this but was unable to meet the requirements.

Check out the link here: https://jsbin.com/cecafeqobo/edit?js,console Below is the snippet of my code:

var mapData = [];

var userList =[{id:2,name:'Admin', users:[{id:2, name:'Test#1'},{id:3,name:'test#4'}]},{id:2,name:'Manager', users:[{id:2, name:'test#2'}]},{id:2,name:'Head', users:[{id:2, name:'test#3'}]}];
userList.forEach(function(element) {
  console.log(element.name)
  element.users.forEach(function (element) {
       mapData.push(element);
  })
})

mapData.forEach((element) => {
  console.log(element.name);
});

Answer №1

Have you considered implementing conditional statements such as if/else? For example:

admin_users = [];
manager_users = [];

userList.forEach(function (root_element) {
  element.users.forEach(function (element) {
    switch (root_element.name) {
      case 'Admin':
        admin_users.push(element);
        break;
      // Repeat for other user types.
    }
  })
})

The users identified as admins will be stored in the admin_users variable, while the manager users will be saved in the manager_users variable.

Answer №2

The reason for the current output is because all users are being logged as a single entity in the last forEach loop. This results in displaying all headings first followed by all user names.

Instead of appending users to an array, try logging them individually.

userList.forEach(function(element) {
  console.log(element.name)
  element.users.forEach(function (element) {
       console.log(element.name);
  })
})

var userList =[{id:2,name:'Admin', users:[{id:2, name:'Test#1'},{id:3,name:'test#4'}]},{id:2,name:'Manager', users:[{id:2, name:'test#2'}]},{id:2,name:'Head', users:[{id:2, name:'test#3'}]}];

userList.forEach(function(element) {
  console.log(element.name)
  element.users.forEach(function (element) {
       console.log(element.name);
  })
})

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

There is a necessary pause needed between carrying out two statements

I am currently working with extjs 4.2 and I have encountered a situation where I am loading the store object in the following manner: var userDetailStore = Ext.create('Ext.data.Store', { model: 'Person.DetailsModel', autoLoad: ...

Concentrate on Managing Text Input Fields in Zend Form

I designed a form using Zend Form and want the focus to be on a text area within the form when the page loads. I attempted to use JavaScript for this purpose, but it only briefly shows the focus before removing it again, preventing any typing. I considere ...

How can you capture the VIRTUAL keyCode from a form input?

// Binding the keydown event to all input fields of type text within a form. $("form input[type=text]").keydown(function (e) { // Reference to keyCodes... var key = e.which || e.keyCode; // Only allowing numbers, backspace, and tab if((key >= 48 && ke ...

Swapping out pages with JSON outcomes is a common practice when utilizing ASP.Net MVC in conjunction with JQuery Ajax

When making an ajax call to update an entity and returning the success state in the MVC controller, I encountered a problem that resulted in the page changing with the URL becoming that of the MVC controller action and displaying the JSON result as content ...

The console object in Chrome_browser is a powerful tool for debugging and

Having difficulty saving an amchart graph to the localstorage and retrieving the data successfully. https://i.stack.imgur.com/lJ3bJ.png In the original object, there is a mystery b, while in the new object, it appears as a normal object. In Internet Expl ...

Tips for inserting a new entry into the KendoUI DataSource module

I have set up a KendoUI DataSource on my webpage that retrieves data in JSON format from a method. Here is the script I am using: <script id="template" type="text/x-kendo-template"> <tr> <td>#= ID #</td> ...

The close icon for v-chip in Vuetify isn't displaying as expected

After upgrading Vuetify from version 1.5 to the latest 2.1.12, I noticed that the close icons on my v-chips are missing. They are nowhere to be seen. Even when creating a basic v-chip, the icon does not appear. Here's an example: <v-chip close> ...

Angular 2 issue with nested form elements

Looking to build a form that includes nested sub/child components within it. Referring to this tutorial: https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 https://plnkr.co/edit/clTbNP7MHBbBbrUp20vr?p=info List of modificatio ...

Triggering the 'change' event on a hidden value in jQuery can cause issues with knockout dependent observables

Let me share the story of how we stumbled upon this issue... Basically, we were invoking trigger('change') on all our form inputs to notify other knockout observables that their values had been reset. However, we suspect it could be a bug in Knoc ...

Exploring the location where an XMLHttpRequest/Ajax link is executed

I am relatively new to the world of Ajax/XMLHttpRequest and I am currently trying to wrap my head around its functionality. My current project involves developing an inventory program that essentially allows users to add tools to a digital box. On the mai ...

Tips for creating a Material UI (next) dialog with generous top and bottom margins that extend off the screen

I am encountering a challenge with the layout. What am I looking for? I need a modal dialog that expands vertically, extending beyond the screen, centered both horizontally and vertically, with minimal margin on the top and bottom. Is this feature not d ...

"Troubleshooting an issue with ng-model not functioning properly with radio buttons in Angular

I'm a newcomer to Angular and I'm attempting to retrieve the value of the radio button selected by the user using ng-model. However, I'm not seeing any output in "selected contact". Check out My HTML below: <!doctype html> <html n ...

Issue with pop-up functionality on web page using HTML, CSS, and JavaScript

Recently, I created a unique popup using HTML. You can see the complete code (excluding CSS) here: https://codepen.io/nope99675/pen/BawrdBX. Below is the snippet of the HTML: <!DOCTYPE html> <html> <head> <meta charset=&quo ...

JavaScript client side event that references the sender object ID in an aspx file

Can someone provide assistance with an issue in the code block below? function(s, e) { form1.hfRaiseEvent.value = s.ID; } This particular function is triggered when the Client Side Click Event occurs. From my understanding, s refers to the Sender Obj ...

How can I make multiple elements change color when hovering with CSS?

Hey there! I have a little design challenge that I need help with. On my website (), I am trying to make multiple elements of a specific item change color when the user hovers over the text. If you hover over the "more" menu item, you'll notice that o ...

Verify the presence of both class and id before modifying the content of the h1 tag and automatically redirecting the page

I'm encountering some issues triggering my JS/JQ on an HTML5 page. Essentially, I want to verify the existence of the following ID and class: ID: page_blog CLASS: page current <section class="page current" id="page_blog" style="z-index: 99; lef ...

Creating a standard text input with full validation and error management in ReactJS

Currently, I have an input Textbox where the "type" is being set from my Props. I am looking for assistance in implementing validation and error handling for this textbox based on the props provided. For instance, if type=email is specified in the props, ...

Utilizing a function that changes a UNIX timestamp to a month/day/year layout

I have been working with ExpressJS and am facing a challenge in converting the UNIX format date to mm/dd/yyyy format when retrieving the date value. I attempted to create a function for this conversion, but encountered an issue where my methods cannot be c ...

Exploring VueJS Router History Mode with NGinx web server

After conducting research, I discovered several issues similar to the one I am facing. Currently, I have a docker-compose setup on Digital Ocean with NGinx, VueJS, and a Static Landing Page. Everything was working fine until I added a new route with a fo ...

Developing a robust system for managing classnames

I have a question regarding the article I found on Quora about Facebook's CSS class names structure. They mentioned that both Facebook and Google use a build system to convert developer-friendly class names into shorter ones to save bandwidth and crea ...