Indraraj26
Indraraj26

Reputation: 1966

array object array issue

i want under admin should have test#1 & test#4, under manager should have test#2 and under head should have test#3. I have tried but couldnt do it as per requirement

link : https://jsbin.com/cecafeqobo/edit?js,console below is 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);
});

Upvotes: 0

Views: 91

Answers (2)

minitauros
minitauros

Reputation: 2030

Have you tried using some if/elses? E.g.

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;
      // Same for other types of users.
    }
  })
})

Your admin users will then be saved in the admin_users variable, and your manager users in the manager_users variable.

Upvotes: 1

Adrian
Adrian

Reputation: 8597

That's because you're logging all the users as a one in the last forEach. Which is giving you this output. First you output all the 'headings' then you output all the users.

Rather than appending users to an array, you should consider logging it.

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);
  })
})

Upvotes: 0

Related Questions