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

Storing freshly acquired JSON data via AJAX into an already existing array

I am currently converting the dynamic data being displayed into JSON, then using AJAX to send it to a specific URL. Subsequently, I retrieve the saved JSON data through AJAX and update my display accordingly. However, an error is occurring stating that &a ...

I am having an issue with an input field not reflecting the data from the Redux state in my React app,

I am currently working on a todo list project using the MERN stack with Redux for state management. One issue I am facing is that the checkboxes for completed tasks are not reflecting the correct state from Redux when the page loads. Even though some tasks ...

Determining the duration since generating a unique objectid in mongodb

I am currently developing an application that offers users the option to reset their passwords. The process is quite straightforward - after entering his email address, the user will receive a link containing the new objectid number. For example: /reset- ...

How can I execute JavaScript within a for loop in the server-side code?

protected void Button1_Click(object sender, EventArgs e) { for (int i = 0; i < 100; i++) { Page.ClientScript.RegisterClientScriptBlock(GetType(), "myScript", "<script>alert('hello world');</script>"); } } Is th ...

Tips for passing parameters in a BootstrapDialog.show({ }) function popup

I am trying to display a popup using BootstrapDialog and pass a parameter with it. I have used the data attribute in my code snippet as shown below: BootstrapDialog.show({ closable: false, title: "This is my custom popup", message: $(' ...

How can I customize the ngSrc directive in Angular to include a request header?

Is there a way to attach an authentication token to the URL request in angular js when using the ngSrc directive? If so, how can this be done? ...

React Select streamlines dropdown options for multi-selection by abbreviating names

Is there a way to shorten dropdown names when selected similar to the example shown in the image below This is the snippet of my code : multiValue: [ { value: "BUF", label: "BUF" }, { value: "CCT& ...

Steps for configuring type definitions for an Apollo error response

Apollo's documentation explains that an error response can take the following form: { "data": { "getInt": 12, "getString": null }, "errors": [ { "message": "Failed to get s ...

Using TypeScript and controllerAs with $rootScope

I am currently developing an application using Angular 1 and Typescript. Here is the code snippet for my Login Controller: module TheHub { /** * Controller for the login page. */ export class LoginController { static $inject = [ ...

What are some reasons for the slow performance of AWS SQS?

My current project involves measuring the time it takes to send a message and receive it from an SQS queue. Surprisingly, the average time it takes is between 800-1200 ms, which seems like an excessively long period. Below is the code I have been using for ...

Conflict between Angular's ng-repeat directive and Sass styling

Currently, I am working on a project and encountering an issue that is causing some difficulty: In order to create a navigation bar with equally distributed list elements based on the number of items, I am utilizing ng-repeat for data binding and Sass for ...

Access Vuex Getters in a separate JavaScript file

Within the file /store/user/getters.js: function getLoggedIn (state) { return state.loggedIn } In a different file, router-auth.js, I attempted to access the value (true or false) of getters.getLoggedIn in the following manner: import user from '.. ...

Troubleshooting the Node.js Server Error Encountered when Enabling AngularJS html5Mode(true)

When using routeProvider and stateProvider in AngularJS with HTML5 mode set to true, everything functions correctly until the page is refreshed. On a Node.js server, I am unsure of what needs to be written on the server side to prevent receiving a "Can no ...

Transfer responsibilities of events to the canvas and then fetch the Element in the handler

Currently, I am utilizing the Raphaël library to create a network graph, where nodes are depicted as circles. Users have the ability to dynamically add nodes by clicking on the canvas. When a new node is added, an Element object is pushed into both a Set ...

Convert the easeInExpo function from jQuery easing to vanilla JavaScript and CSS

Currently, I am in the process of converting a piece of code from jQuery to plain JavaScript and CSS. The specific code snippet I am focusing on involves creating easing functions without relying on jQuery. const customEasing = { easeInExpo: function ( ...

What about a lightbox with enhanced jQuery features?

As a newcomer to jQuery, I've never experimented with lightboxes before. However, I was tasked with creating something fun for April Fools' Day at work. Naively, I accepted the challenge thinking it would be simple, but now I find myself struggli ...

Use ag-Grid to customize your column headers with checkboxes, allowing you to easily select or deselect all items in that column. This feature is not limited to

In my experience with ag-grid, I often find myself needing to customize the first column header to include a checkbox. This allows me to easily perform actions such as selecting all or deselecting all rows in the grid. It's important to note that this ...

Copy both the image and JSON object to the clipboard

I am attempting to utilize the clipboard API to write an image and JSON object to the window clipboard. I am working with Vue and Electron and have successfully written an image and plain text, but I encounter an error when trying to write a JSON object: ...

``How can one validate a radio button within a reducer by utilizing the event object that is passed into the reducer process

In my React app, I am using the following reducer: const initialState = { genderRadio : false, ageRadio : false } const reducer = (state = initialState, action) => { switch(action.type) { case "VALI_RADIO_INP": console. ...

I'm curious about the origin of this.on event handler. Is it part of a particular library or framework?

While casually perusing through the application.js file in the express source code, I stumbled upon this interesting piece of code. I'm curious about the origin of this '.on' event. Is it part of vanilla JavaScript or is it a feature provid ...