What is the best way to traverse a JSON object in AngularJS using a for loop?

I am facing an issue with iterating through an array and checking a condition for each element. If the condition is true, I need to return one value, otherwise another value. However, the loop is not terminating when the condition is met. Can anyone assist me in solving this problem?

 $scope.bgImages = []; //contains some objects
 $scope.job = []; //also contains some objects
 //if both elements match, we return one value
 $scope.getJobDepartmentImg = function() {
     var jobDepartment = $scope.job.department;
     for (var i in $scope.bgImages) {
         var department = $scope.bgImages[i].departmentName;
         var job_header = $scope.bgImages[i].s3ImageUrl;
         if (jobDepartment === department) {
             return job_header;
         } else {
             return default_job_header;
         }
     }
 };

The loop is not terminating when the condition is satisfied, causing it to run continuously. Any help would be appreciated.

Answer №1

Ensure a second return statement is placed outside the else clause

$scope.getJobDepartmentImg = function() {
        var jobDepartment = $scope.job.department;
        for (var i in $scope.bgImages) {
            var department = $scope.bgImages[i].departmentName;
            var job_header = $scope.bgImages[i].s3ImageUrl;
            if(jobDepartment === department){
                return job_header;
            }
        }
        return default_job_header;
}

This function will search through an array and return the job header if found, or the default header if the loop completes without finding a match.

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

Pattern matching for traversing object properties

Is there a dependable method to match property-syntax using a Javascript regex? My goal is to identify whether a string contains a path structure, without the need to extract the specific members. For instance, if I have a string such as: someobject.somek ...

Having issues with the functionality of my Vuejs filter in my code

Within my Vue.js code, I am facing an issue. I have questions retrieved from an API along with their respective categories stored in an array called 'questions'. My goal is to be able to filter the questions based on the category that is clicked. ...

"Repeatedly encountering 'undefined' when subscribing to the selected option of a select list in Knockout.js

In my dropdown list, I have prepopulated a selection of strings. My select list is bound as follows: <select id="industryDropDown" data-bind="options: $root.orgIndustrySuggestions, value: $root.selectedIndustryTag, optionsCaption: ''"> ...

The error message is stating that there is a TypeError because it cannot read the property "bind" of an undefined value when using the ng

When trying to implement the ng-cropper directive, an angular binding for the cropper javascript image cropping library, I'm encountering the error message TypeError: Cannot read property 'bind' of undefined. It seems to be related to the fo ...

Managing multiple JQuery Dialog boxes can be tricky, especially when you can only close one instance at a time

I'm currently working on integrating multiple instances of Jquery's Dialog box on the same website. The issue I'm facing is that I have two instances that I initialize using a new function like this: function Modal(param) { this.modal = ...

Angular: Incorporating a custom validation function into the controller - Techniques for accessing the 'this' keyword

I'm currently working on implementing a custom validator for a form in Angular. I've encountered an issue where I am unable to access the controller's this within the validator function. This is the validator function that's causing tr ...

The data in the second run of the jQuery datatable does not refresh successfully

I have encountered an issue while trying to load data from the server. It works perfectly on the initial load, but upon reloading, it fails to function. Please bear with me as this is a legacy project. Even after attempting a normal call and refreshing th ...

Why is my website returning a 404 error while attempting to retrieve a JSONObject?

@Override protected JSONArray doInBackground(Long... ids) { id=ids[0]; apiURL="http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=534FA68616FC166C4A9F11CEB01B9929&steamid=76561197976528744&format=json" ...

How can I create a custom validator in Angular 2 that trims the input fields?

As a newcomer to Angular, I am looking to create a custom validator that can trim the input field of a model-driven approach form. However, I have encountered difficulties during implementation. When attempting to set the value using setValue() within th ...

What distinguishes event-stream.through from event-stream.map?

After reviewing the documentation on event-stream, it appears that the main distinction between these two methods is whether they operate synchronously or asynchronously. However, I am still unclear on the true significance of this difference. ...

Tips for representing the single quote/apostrophe in JSON.NET

What is the best way to encode an apostrophe (') as \u0027 using JSON.NET? This will ensure that the resulting JSON string appears like this: {"Id":8,"CompanyName":"Jane\u0027s bakery"} ...

What is the reason for elements such as "if" and "else" not being visually

I am currently developing a browser-based code editor with a unique feature. Task: The objective is to highlight specific keywords like if, else, for... when they are entered into the editor. textarea.addEventListener("input", function() { ...

Schedule Master: A sophisticated tool for time management

I have been following the instructions to implement a date time picker from this tutorial. I downloaded the necessary js and css files and placed them in the respective directories. However, when I click on the calendar icon, the calendar does not pop up. ...

What is the best way to utilize MUI breakpoints for displaying images based on different screen sizes?

I need help displaying an image based on the screen size using MUI breakpoints. I'm struggling to understand how to implement this with MUI. Can someone assist me with the breakpoints? interface EmptyStateProps { title: string; description: string ...

In tsconfig.json, the compiler is not utilizing other tsconfig.json files when using the "extends"

I'm attempting to streamline my project by breaking up my tsconfig.json into separate files. I have one for the source files and another for the tests. However, when I utilize the extends field, it seems that only the base tsconfig.json is being utili ...

I am having trouble combining my streams with es.merge

Here is the gulp task that I am working on: var es = require('event-stream'), concat = require('gulp-concat'), templateCache = require('gulp-angular-templatecache'); var scripts = gulp.src(paths.js + '/**/*.js&a ...

Tracking the progress bar as files are being uploaded via AJAX using HTML5

Currently, I have a progress bar that increments based on the number of files and their sizes. I am looking to implement an overall progress bar to display while uploading files to the server using AJAX and HTML5. Each file is uploaded individually to th ...

Update your Django database with new information either using views or a JSON dictionary

My simplest table structure is as follows: class Player(models.Model): number = models.CharField(max_length=2) player = models.CharField(max_length=50) position = models.CharField(max_length=2) height = models.CharField(max_length=50) weight = models.Char ...

Tips for accessing the reference of a child when it is a functional component

Trying to implement a Higher Order Component (HOC) to access the ref of any component. It works perfectly fine when regular JSX is passed, but encounters issues when a functional component is passed: class GetRef extends React.Component { state = {}; ...

Ways to customize PreBid.js ad server targeting bidder settings

In an effort to implement a unique bidder setting key name within my prebid solution, I have taken the necessary steps as outlined in the documentation by including all 6 required keys. Is it possible to change the key name 'hb_pb' to 'zm_hb ...