Loop through a non-array or non-object / handling both arrays and non-arrays equally

Sometimes, I find myself needing to handle arrays and single objects in a similar manner. For instance, I may have an object property that can be either an array or just a string (like the scale property):

[
 {
    "name": "Experiment type14",
    "id": "00000000014",
    "scale": ["Whole Brain", "Cell"],

 },
 {
    "name": "Experiment type15",
    "id": "00000000015",
    "scale": "Cell",
 }
]

I'd like to display my scale as follows:

<span ng-repeat="scale in experimentType.scale">
 <!--some decoration here--> {{scale}}
</span>

Naturally, this approach wouldn't work for single string values. Is there a more elegant solution to seamlessly handle both strings and arrays without worrying about the data type?

Answer №1

If you want to create a personalized filter, you can follow the instructions provided below:

var app = angular.module("app", []);
function MainCtrl() {
  this.message = "Welcome";
  this.data = [{
    "id": "00000000016",
    "name": "Experiment type16",        
    "scale": ["Whole Brain", "Cell"],
   },{
    "id": "00000000017",
    "name": "Experiment type17",
    "scale": "Cell",
   }];  
}

function toList() {
  return function(input) {
    console.log(input);
    if (angular.isArray(input)) {
      return input;
    } else {
      return [input];
    }
  };
}

angular.module("app").controller("MainCtrl", MainCtrl);
angular.module("app").filter('toList', toList);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
  <div ng-controller="MainCtrl as vm">
    <div class="container">
       <h3>{{ vm.message }}</h3>
      <div ng-repeat="item in vm.data">
        <p>{{ item.name }}</p>
        <ul>
          <li ng-repeat="scale in item.scale | toList">{{ scale }}</li>
        </ul>
      </div>
    </div>
  </div>
</body>

Answer №2

Here is a function I created and implemented within the current scope:

$scope.myCustomFunction = function (data) {
        if (Object.prototype.toString.call(data) === '[object Array]') {
            return data;
        }
        return [data];
    };

To utilize this function, I simply do the following:

<span ng-repeat="item in myCustomFunction(someData)">
 <!--add styling or other actions here--> {{item}}
</span>

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

When a td element is clicked, the Textbox will also be clicked

Similar Question: Dealing with jQuery on() when clicking a div but not its child $(oTrPlanning).prev().children('td').each(function () { this.onclick = setCountClick; }); When a TD element is clicked, the function setCountClick() i ...

How to create a tooltip for overflowing text in Angular UI-Select?

I am working with a ui-select-match element, and I am facing an issue where the full content of a row is not showing when hovering over it due to text overflow being cut off by the border. It seems like this should be a built-in feature of ui-select, but I ...

How to create a donut chart in Highcharts without an inner pie section?

I've been scouring the internet in search of a solution to create a basic donut chart using the Highcharts library. Most examples I come across show donut charts with both an inner pie and outer donut (see here). Is there a way to remove the inner pi ...

Retrieve the response retrieved from AJAX/jQuery and insert it into the designated form input field

When a user inputs an address into this form and clicks on the verify address button, the following script is executed: $('#verify').click(function () { var address = $('input[name=address]'); var city = $('input[name= ...

Automatically fill in options for up to 3 dropdown menus depending on the choices made in the previous dropdown menu

I've looked through similar questions but haven't found the solution I need. Here's a sample fiddle with some example data for years, months, and days. Instead of manually adding select option divs for each year, I want the div id to dynami ...

Formatting dates in the Bootstrap Date Picker within Angular 6

When using Angular 6, I incorporate a date picker by adding the bsDaterangepicker class for selecting a date range. <input type="text" (ngModelChange)="dateFilterChanged($event)" [(ngModel)]="myDateField" value="{{ myDateField | date:'yyyy-MM-dd&a ...

globalThis undefined following git hiccup

While working on a web app in React, I followed a certain guide to execute Python code successfully within the app. However, during a git operation, I accidentally added unnecessary files like node_modules and package lock files, which led me to delete ev ...

VueJS Components experiencing issues with displaying images

Recently, I delved into learning VueJS and successfully created a basic restaurant menu page all within a single file. Excited by my progress, I decided to refactor the project using vue-cli, but hit a snag with the images not displaying properly. The cur ...

What is the best way for me to implement a .config feature to allow for customization of my

I have developed a small code library for angular js. Within my library's main module, I have implemented a method called .config that relies on my moduleConfigProvider. I anticipate the user of my library to invoke .configure on my config provider du ...

Share on iOS using $cordovaSocialSharing

After implementing the ngcordova plugin social sharing, I encountered an issue where everything worked fine on Android but on iOS, the title (subject) was not appearing. function shareEventDetail() { $ionicPlatform.ready( function () { ...

A guide on how to mention users in Discord.js

I attempted to get the bot to mention a member using @, but when I used message.channel.send(<@id>+"text") it showed an error message saying unexpected sign '<'. Is there a way to successfully mention members with the bot? ...

What is the best way to execute a specific set of unit tests in Gulp-Angular using Karma?

In the midst of my AngularJS 1.4 project, fashioned through the Gulp-Angular yeoman generator, I find myself facing a dilemma. With karma and gulp settings already in place, executing gulp test runs all *.spec.js files within the project. However, my desir ...

Ensure that a group of checkboxes is mandatory

I currently have a series of checkboxes set up like so: <label>What is your preferred movie genre?</label> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="genre1" name="genre" ...

An array containing a list of URLs linked together

Here is the string I am working with: http://localhost/layerthemes/wp-content/uploads/2014/05/46430454_Subscription_XXL-4_mini.jpghttp://localhost/layerthemes/wp-content/uploads/2014/05/Eddy-Need-Remix-mp3-image.jpghttp://localhost/layerthemes/wp-content/ ...

Learn how to eliminate all text characters from a string using jQuery, leaving only the numerical values behind

My webpage features a variety of different products, each with their own values. When trying to calculate the total sum of these products and display it in the shopping cart, I encountered an error displaying NaN. How can I remove this NaN from the strin ...

looking to showcase the highest 'levelNumber' of elements within an array

arr1 = [ { "levelNumber": "2", "name": "abc", }, { "levelNumber": "3", "name": "abc" }, { "levelNumber": "3", "name": &quo ...

Encountering a display issue within a port using Express

Recently, I enrolled in an advanced ExpressJS course. While exploring the course website, I stumbled upon the "hello world" section. Intrigued, I decided to copy and paste the code provided below: const express = require('express') const app = ex ...

Utilize a vanilla JavaScript object as the primary model in Ember

Can a plain JS object, such as a literal object, be used as a model in EmberJS? I've noticed that all the examples in the documentation utilize Ember.Object or a datastore. I understand that I may not have access to features like observables with pl ...

Need a tool for validating forms?

I am currently facing some confusion with the UI Validation plugin that we are using. Within our application, we employ Spring MVC, Jquery & Bootstrap. As we delve into UI development, we have encountered uncertainty in selecting an appropriate Validation ...

Tips for ensuring that the click event function properly for numerous elements sharing the same class

I'm currently working on adding a flip effect to multiple tiles whenever a user clicks on them as part of building a dashboard-style webpage. I am having trouble making the click event work for all tiles with the same class name. Even though all the ...