SBB SBB - 1 year ago 71
jQuery Question

Javascript Find and Push Items into Array

I have a dataset being returned from an AJAX call that contains a list of users and their role in association to the project.

A user can hold multiple roles and therefore be in the result set in various places.

I am trying to create an Array/Object that I can push the user into the first time along with their role and then any time it sees that user again, it just adds their role to their existing array.

For example, and this is way off I'm sure but its the concept..

var tempRoles = [];

// Loop over our users. If they are already in the array, just add their additional row.
QID: this.QID,
role: this.Role

In the end, I need to have a list of all the individual users and then an array of all their roles that they hold.

This is what I would think the array would look like

Users <-- Object?
Bob123 <-- User Name
Roles <-- Array
Admin <-- Role
Mod <-- Role
Super Mod <-- Role

The only catch to this is I need to in a format where I can look up the user directly and see their roles.


I know my example isn't that helpful but hopefully it shows what I am trying to accomplish here.

This is what the object looks like right now, printed to the console. As you can see, the same ID is in there multiple times with different roles.

I need to be able to have a single user and their multiple roles that they hold.
enter image description here

Not sure the correct formatting on this but its how I would assume the output would be:

users [
roles [
'admin', 'mod', 'superMod'
roles [
'admin', 'mod'

Answer Source

You can just loop over the array and create an object keyed off the QID. As you loop over them, if the user already exists in the map, just push the role onto the array.

  var users = [
    {QID:'user1', ROLE: 'role1'},
    {QID:'user1', ROLE: 'role2'},
    {QID:'user2', ROLE: 'role1'}

  var userMap = {};
  users.forEach(function(user) {
    if (!userMap.hasOwnProperty(user.QID)) {
      userMap[user.QID] = {QID:user.QID, roles:[]};


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download