agon024 agon024 - 1 year ago 73
AngularJS Question

AngularJS - matching logged in user with users in a JSON array

So I am setting a key in a users local storage when they log in that contains the username they just logged in with. What I need to do is two things take that value with their username in it and search through a JSON array of usernames that is being returned from an API. If the local storage username matches one of the names in the JSON array and the second part if the JSON "status" key has a value of "IN PROCESS" then I need to run a simple jQuery line.

Here is the controller that is returning the JSON containing a list of usernames from the API:

function carDetails($scope, CarDetailService, API) {
CarDetailService.getCar().success(function(details) {
$scope.details = details;

The jQuery line I need to run is just:

$('#takeAction').css('display', 'block');

enter image description here

As you can see in the picture above the array that is being returned is "All Current Approvers" and the other key is "Status". And you can see the username (or email) in the local storage matches one of the "All Current Approvers". And even though only one email exists in the array now the other ones in the app will have more than 5 usernames in the array which is why I need to search through the array.

I can create a variable that gets the username from local storage:

var user = localStorage.getItem('user')

But from there I am not sure how to match it up with the values in the "All Current Approvers" array, check to make sure status is "IN PROCESS" and then run my jQuery line.

Thanks for any help.

Answer Source

Sounds like a basic for loop will get you want you want.

var approvers = $scope.details["All Current Approvers"],
    status    = $scope.details.Status;

for (var i = 0; i < approvers.length; i++) {
    if (approvers[i] === user && status === 'IN PROCESS') {
        // do jQuery

Take note of the bracket syntax for referencing a JSON property that has spaces in it.

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