Exploring the Comparison of Arrays in AngularJS

I am currently working with two arrays: one for Usernames and another for userRoles. The structure of the arrays is as follows:

Usernames = [
  {
    "id": 1,
    "userName": "Jack",
    "description": "jack is a nice guy",
    "userRoleIds": [
      1
    ]
  },
  {
    "id": 2,
    "userName": "Caroline",
    "description": "Good girl",
    "userRoleIds": [
      2,3
    ]
  },
  {
    "id": 3,
    "userName": "Smith",
    "description": "Smithyyyy",
    "userRoleIds": [
      1,2
    ]
  }
]

And here are the userRoles:

userRoles = [
  {
    id: 1,
    roleName: "Admin"
  },
  {
    id: 2,
    roleName: "Tester"
  },
  {
    id: 3,
    roleName: "Developer"
  }
]

My goal is to combine these arrays to achieve a specific result format. For example:

 Usernames = [
      {
        "id": 1,
        "userName": "Jack",
        "description": "jack is a nice guy",
        "userRoleIds": [
          {
            "id": 1,
            "roleName" : "Admin"
          }
        ]
      },
     {
    "id": 2,
    "userName": "Caroline",
    "description": "Good girl",
    "userRoleIds": [
         {
            "id": 2,
            "roleName" : "Tester"
          },
          {
            "id": 3,
            "roleName" : "Developer"
          }
    ]
   },...

In addition, I want to be able to filter the array based on searches for combinations of userName and roleName separated by pipe signs. For instance, if I enter:

Caroline, Tester

The expected result would be:

result = [
  {
    "id": 2,
    "userName": "Caroline",
    "description": "Good girl",
    "userRoleIds": [
      2,3
    ]
  },
  {
    "id": 3,
    "userName": "Smith",
    "description": "Smithyyyy",
    "userRoleIds": [
      1,2
    ]
  }
]

What would be considered best practice for accomplishing this task?

Thank you!

Answer №1

In my approach, I like to utilize services and their functions to maintain clean code.

app.service('UserService', function (PermisionsServices) {
    var self = {
        'list': [],
        'load': function (Users) {//Provide your array of Users
            angular.forEach(Users, function (user) {
                angular.forEach(user.userRoleIds, function (role) {
                    self.user.userRolesIds.push(PermisionsServices.get(role));
                });
                self.list.push(user);
            });
        }, 'get': function (id) {
            for (var i = 0; i < self.list.length; i++) {
                var obj = self.list[i];
                if (obj.id == id) {
                    return obj;
                }
            }
        }
    };
    return self;
});

app.service('PermisionsServices', function () {
    var self = {
        'list': [],
        'load': function (permisions) {//Provide your array of permissions
            angular.forEach(permissions, function (permission) {
                self.list.push(permission);
            });
        }, 'get': function (id) {
            for (var i = 0; i < self.list.length; i++) {
                var obj = self.list[i];
                if (obj.id == id) {
                    return obj;
                }
            }
        }
    };
    return self;
});

Once set up, you can integrate it into your controller: $scope.users=UserService;

This allows access to each user as a distinct object with multiple permissions.

NOTE: The process of building the service may vary based on your app's logic and controller. You could simply omit the "load" function and input the list object directly by copying and pasting your arrays.

This is my method for retrieving data from an API using resources.

Regards

Edit: To display on the UI, simply use:

<div ng-repeat='user in users.list'>
  {{user.name}} has {{user.permissions}}
</div>

as all necessary information is already contained within.

Edit 2: For data search functionality, add a filter like so:

<div ng-repeat='user in users.list | filter: filterList'>
      {{user.name}} has {{user.permissions}}
</div>

In the controller:

$scope.filterList = function (user) {
        if ($scope.filterTextBox) {
            return user.name.indexOf($scope.filterTextBox) == 0;
        }

        return true;
    }

I hope this solution fits your needs

Answer №2

If I were to implement this functionality using pure JavaScript, I would write it like this. It can be achieved with just a single assignment line for each task.

var Usernames = [
  {
    "id": 1,
    "userName": "Jack",
    "description": "jack is a nice guy",
    "userRoleIds": [
      1
    ]
  },
  {
    "id": 2,
    "userName": "Caroline",
    "description": "Good girl",
    "userRoleIds": [
      2,3
    ]
  },
  {
    "id": 3,
    "userName": "Smith",
    "description": "Smithyyyy",
    "userRoleIds": [
      1,2
    ]
  }
],
userRoles = [
  {
    id: 1,
    roleName: "Admin"
  },
  {
    id: 2,
    roleName: "Tester"
  },
  {
    id: 3,
    roleName: "Developer"
  }
],
modified = Usernames.reduce((p,c) => (c.userRoleIds = c.userRoleIds.map(e => e = userRoles.find(f => f.id == e)),p.concat(c)),[]),
   query = ["Caroline","Tester"],
filtered = modified.filter(f => query.includes(f.userName) || f.userRoleIds.some(e => query.includes(e.roleName)));
console.log(JSON.stringify(modified,null,2));
console.log(JSON.stringify(filtered,null,2));

Answer №3

One way to accomplish this task is by utilizing the lodash library.

var specificRole = _.find(allRoles, function(role) { 
            return role.name === 'Tester'; 
        });
        
_.find(allUsers, function(user) { 
    return user.name === 'Caroline' || _.indexOf(user.roles, specificRole.id) >= 0; 
});

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

You are not able to access the instance member in Jest

My first encounter with Javascript has left me puzzled by an error I can't seem to figure out. I'm attempting to extract functions from my class module in order to use them for testing purposes, but they remain inaccessible and the reason eludes ...

Making an asynchronous request from jQuery to a Slim Framework API endpoint

I'm currently working on incorporating Slim into my project and I'm facing some challenges with setting up the AJAX call correctly: $.ajax({ url: "/api/addresses/", type: 'POST', contentType: 'application/j ...

Screenshots of playwright failing to work on Github.''

Within my playwright.config.ts file, I have specified the following: use: { ... screenshot: 'only-on-failure', } When running tests locally and they fail, screenshots are successfully saved in /test-results. However, the issue arises when th ...

VueJS component fails to properly sanitize the readme file, as discovered by Marked

Could someone explain why the output from the compiledMarkdown function is not sanitized, resulting in unstyled content from the markdown file? <template> <div style="padding:35px;"> <div v-html="compiledMarkdown" ...

Updating Rails record using Ajax with select_tag and onchange functionality

I'm working on an index view where I want to update a table data dynamically using select_tag onchange feature without the need to refresh the page. Do I need to use Coffeescript to detect the onchange event, capture the new value, and then send it to ...

Updating elements within an array on the fly

In this scenario, let's consider two arrays: array A = [2, 5, 6] and array B = [1, 2, 3, 4, 5, 6, 7, 8]. The values of array B are initially hidden within boxes and become revealed when clicked. The goal is to replace certain values in array B with un ...

Update the minimum date in an AngularJS input field to the current date

How do we go about setting the min attribute for an input type = "date" to today's date in AngularJS? <input type="date" ng-model="data.StartDate" name="StartDate" min=?? /> Edit1 To implement the suggestion provided below, I included this in ...

Error: The initial parameter must be a string, Buffer, ArrayBuffer, Array, or Array-like Object. An object type was passed in instead in CryptoJS

In my quest to encrypt and decrypt data in react-native, I embarked on using the crypto node module by incorporating it into my react native project through browserify. While attempting encryption with the code snippet provided below, an error surfaces sta ...

What is the best way to incorporate animation into a React state?

Looking to implement a fade-in animation for the next index but struggling with tutorials using "react transition group" that are focused on class components or redux. https://i.sstatic.net/q791G.png const AboutTestimonials = () => { const [index, se ...

In React Router version 4, it is stated that each router is only allowed to have a single child element when using multiple routes

I'm currently working on implementing a sidebar alongside the main content area using react-router-dom. Instead of just rendering <Sidebar/> directly, I want to pass it the location prop due to another issue where clicking a <Link/> in the ...

Using ui-select for data binding in AngularJS

I recently created a program using ui-select in angular, but I encountered some unexpected issues with the ng-model. It seemed to have a strange behavior and I struggled to bind the value set in the ng-model from the .js controller. Below is the snippet o ...

Change the websocket origin to localhost in a javascript setting

My server is hosting the domain example.com. Every time a user loads a page on this server, it utilizes a WebSocket client in JavaScript to connect to another WebSocket server. However, the other server has CORS enabled, which prevents the connection bec ...

What is the best way to eliminate the lower margin in the UI-Boostrap Angular Tab directive?

The ui.bootstrap.tabs directive, which can be found here, seems to have a default margin before displaying its content. https://i.stack.imgur.com/NECGA.png Here is the HTML snippet: <uib-tabset active="activeJustified" justified="false" id="tabSet" s ...

Utilizing Internationalization in Socket.io

I currently utilize the i18n-2 package for Internationalization in my project by implementing it as follows: router.get('/route', function (req, res, next) { res.redirect('/route/?lang=' + req.i18n.getLocale()); }); Now, ...

What is the best way to add controllers to AngularJS?

What is the best way to troubleshoot this setup? app.js var app = angular.module('app', ['ui.router', 'app.controllers']); /* Why is FooCtrl not being recognized here? */ controllers.js var controllers = angular.module(&a ...

Unable to append Jquery attribute to a div component

My code snippet is creating a div with specific classes and elements: '<div class="ctrl-info-panel col-md-12 col-centered">'+ '<h2>You do not have any projects created at the moment.</h2>'+ '<div id="t ...

JavaScript can be used to arrange a table in both ascending and descending order by simply clicking on the header

window.addEventListener('DOMContentLoaded', () => { let dir = "dsc"; th = document.getElementsByTagName('th'); for(let c=0; c < th.length; c++){ th[c].addEventListener('click',item(c)); } ...

Using jQuery, what is the best way to conceal a Div while the scroll bar is in motion?

Is there a way to make the #menu fade when the scroll bar is in motion, creating a cleaner interface? I'm hoping to find code that will detect scroll bar movement, allowing the #menu to gradually fade out after 1 second of scrolling and come back aft ...

Curved Edges Ensure Non-Interactive Elements

element, there is a query about utilizing a color wheel from a repository on GitHub. The goal is to disable any actions when clicking outside of the canvas border radius in this color wheel. Various steps need to be taken to prevent unwanted outcomes: - S ...

Using Chart.js to display JSON data in a graphical format

I am facing an issue and need some help. I have gone through various tutorials and questions, but none of them seem to address my specific problem. When making an ajax request to my PHP file, I receive a JSON response like this (as seen in the console log) ...