Filter object in Angular to remove empty values

Below are the specific data sets:

 $scope.icons = [{
"id": 1,
"bonuses": [
  { "id": 1, "name": "Rob",  "amount": 10, "foreman": 1, "percA": 1, "percB": 0  },
  { "id": 2, "name": "Mark", "amount": 20, "foreman": 1, "percA": 1, "percB": 0  },
]
  }, {
    "id": 2,
"bonuses": [
  { "id": 1, "name": "Rob",  "amount": 11, "foreman": 1, "percA": 1, "percB": 0  },
  { "id": 2, "name": "", "amount": 30, "foreman": 1, "percA": 1, "percB": 0  },
]
  }, {
"id": 3,
"bonuses": [
  { "id": 1, "name": "Rob",  "amount": 10, "foreman": 1, "percA": 1, "percB": 0  },
  { "id": 2, "name": "Kent", "amount": 35, "foreman": 1, "percA": 1, "percB": 0  },
]
}];

In the controller there is this function:

$scope.getBonusPeople = function() {

var bonusData = [];

angular.forEach($scope.icons, function(item) {

  angular.forEach(item.bonuses, function(bonusLine) {

    if (bonusData.indexOf(bonusLine) == -1 ) {
      bonusData.push(bonusLine);
    }

  })
});

return $scope.bonusPeople = bonusData;
}

The output of this function is displayed as follows:

Rob - 10
Mark - 20
Rob - 11
- 30
Rob - 10
Kent - 35

The goal is to extract only lines where the 'name' value in bonuses is present.

The desired result should be:

Rob - 10
Mark - 20
Rob - 11
Rob - 10
Kent - 35

How can I accomplish this?

A link to a relevant code sample: http://plnkr.co/edit/wZpr0nerqti4L2Yg37iT?p=preview

Answer №1

Make sure to add a validation check to ensure that the name is not an empty string before proceeding. Refer to the code snippet provided below for implementation details.

angular.forEach($scope.icons, function (item) {
    angular.forEach(item.bonuses, function (bonusLine) {
        if (bonusData.indexOf(bonusLine) == -1 && bonusLine.name !== '') {
            bonusData.push(bonusLine);
        }
    })
});

Answer №2

Verify if the name field contains a value. If it does, continue with your current logical process:

angular.forEach($scope.icons, function(item) {
  angular.forEach(item.bonuses, function(bonusLine) {
    if(bonusLine.name!=='') {
        if (bonusData.indexOf(bonusLine) == -1 ) {
          bonusData.push(bonusLine);
        }
    }
  })
});

Plunk: http://plnkr.co/edit/E9bXzn8Jt2B8yJ3IU33s?p=preview

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

Traversing a JavaScript class within a for loop

I am attempting to access the locations listed in json.responseJSON.Sites, starting with LHR on the first iteration and then NJE on the next one, and so forth. The notifications for each location are "LHR" and "NJE", respectively. Is it possible to achieve ...

Deleting sections of a string using JavaScript

I've encountered a rather unique issue where I need to address a bug on a website. The problem is that when a string is generated dynamically, it automatically adds 5 spaces before and after the string. Ideally, this should be fixed in the backend cod ...

Numerous JSON entities

Curious to know if it's achievable to load more than one JSON file with just a single jQuery.ajax() call. Or do I have to make separate calls for each file? Warm regards, Smccullough ...

AngularJS: Using controller services to handle REST API calls

Lately, I've been hesitant about reaching out here for help because there are so many resources available, but I'm feeling lost. I'm attempting to create a small Angular app, but I'm struggling to move beyond the basics. My goal is to ...

There was an error in parsing the JSON data due to an unexpected token "u" at the beginning of the string

I've been working on improving my JavaScript skills, but I hit a snag with an error message that reads "Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse". var requestData = new XMLHttpRequest(); requestData.open('GET& ...

Instructions for manipulating and displaying a source array from a child component using Vue

I have a parent component with an array that I display in the template. My goal is to click on a link that uses vue-router with a dynamic id attribute, and then open a new component displaying only the element of the array that corresponds to that id. Howe ...

Combining various components within an inactive element tag using Vue

I am working on creating expandable rows for a table element using this HTML code snippet. The current approach involves alternating between parent rows and multiple rows within tbody elements. <tbody class="js-table-sections-header">Parent row</ ...

Ways to alter the appearance of individual characters in the text input

My latest project involves dynamically changing the CSS styles of each individual character in a given text input. For example, if the user types "Stack" into the input field, I want the 'S' to appear in red, 't' in blue, 'a' ...

ReactJs - SyntaxError: The JSX content is not properly terminated

I'm just starting out with ReactJs and have come across an issue that I can't seem to figure out. Here's my code snippet: var ListComponent = React.createClass({ render: function() { return ( <li>{this.props.va ...

Tips for launching a fresh window and embedding HTML into it with jQuery?

I'm attempting to use JavaScript to open a new window, but the HTML content is not being added: var callScriptText = $('#callScriptText').html(); var url = '/Action/CallScript/?callScript='; // Open the current call script in a n ...

Variable scope not properly maintained when there is a change in the Firebase promise

I am currently working on developing a controller function to handle signup submissions using Firebase. However, I've encountered an issue where the variables within the scope (controllerAs: $reg) do not seem to update correctly when modified inside a ...

What could be causing the malfunction of my Nextjs Route Interception Modal?

I'm currently exploring a different approach to integrating route interception into my Nextjs test application, loosely following this tutorial. Utilizing the Nextjs app router, I have successfully set up parallel routing and now aiming to incorporate ...

What is the best way to update $state in AngularJs when the user makes changes to the controller?

I am currently working on Angular UI Router and I want to refresh the current state by reloading it and rerunning all controllers for that state. Is there a way to reload the state with new data using $state.reload() and $stateParams? Here is an example ...

Issue with importing a file using JQuery causing the click event to not function properly

I have a file named navigation.html located in a directory called IMPORTS <!-- Navigation --> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-ta ...

Get rid of the folder from the URL using an <a> tag

I have both an English and French version of my website located at: *website.com/fr/index.php *website.com/index.php Currently, I have a direct link to switch between the two versions: -website.com/fr/index.php -website.com/index.php. However, I ...

Tips for adjusting the font size according to the varying number of characters entered

I am currently facing a challenge with adjusting the font size based on the dynamic number of characters. For example, I have a set of characters with a font-size of 40px, and as more characters are added, the font size should decrease to fit within the av ...

When submitting a form with a contenteditable div and text box using JQuery, the POST request is not

I developed a website that allows users to edit and format text, then save it onto the server. Utilizing jquery to send the data to a PHP page for saving, I encountered an issue where the site fails to send the file name along with the formatted text to PH ...

What steps should I take to address the error message "TypeError: express-validator is not a function

I am currently utilizing express-validator version 6.4.0 and encountering an error when running the server. I have attempted to implement custom validation by organizing separate files for validator, controller, and routes. Here is the primary server file ...

Receiving an 'undefined' result in an asynchronous response even with 'await' and 'then' statements implemented

I'm struggling with sending a GET request, parsing the response, and passing it to another function. It seems like I'm having difficulty dealing with the asynchronous nature of the response. I prefer to stick to using Node.js' built-in modu ...

Looking for someone who has successfully upgraded React Native code from version 0.59 to the most recent version

Is there a way to make my React Native project compatible with the latest version? I am facing a challenge in updating an old React Native project running on version 0.59.10 to the most recent version. Despite trying various methods, I have been unable to ...