Exploring Ways to Loop through a JavaScript Map in Angular with ng-repeat

As I work on developing my Angular application, I encounter a situation where I have a Map object with keys and values (as demonstrated below). These key-value pairs in the map object (headerObj) are provided by the user as input to the application.

  var headerObj = new Map();
  headerObj.set(key, value);

I iterate through these pairs using a forEach loop, and the output is as expected:

           $scope.inputHeaders.forEach(function (headerkey, headervalue) {
                     console.log(headerkey, headervalue); 

                });

However, I need to display these map values in the UI, allowing users to edit them. Therefore, I bind the values accordingly:

          <li class="list-group-item" ng-repeat="header in inputHeaders">
              <div ng-repeat="(key, value) in header">
                  {{key}} : {{value}}
             </div>
          </li>

I have tried various methods by searching online, but none have been successful. I am particularly interested in learning how to iterate over a map using forEach in Angular.

To provide more context, my requirement is to pass values to the server in a key-value pair format. If I use object properties, the key of the object remains fixed, which is not suitable for my server's expectations. For example:

       {"key":"Content-Type","value":"application/x-www-form-urlencoded","$$hashKey":"003"}]

On the other hand, my server expects a format like this:

        "Content-Type" => "application/x-www-form-urlencoded"

I have created a Plunkr example for editing purposes: http://plnkr.co/edit/t2g6Dl831HGyjD6uSdf3?p=preview

Answer №1

When working with AngularJS 1.x, it's important to note that Javascript iterators are not directly supported. This means that if you want to use a Map object in your code, you will first need to convert it to an Array. One way to do this is by using the Array.from() method.

To achieve this conversion, you can use the following code snippet in your controller:

$scope.inputHeadersArray = Array.from($scope.inputHeaders);

And then in your view, you can iterate over the elements in the newly created inputHeadersArray like so:

<li class="list-group-item" ng-repeat="header in inputHeadersArray">
  {{header[0]}} : {{header[1]}}
</li>

Answer №2

If you want to work with an array of headers, you have a few options:

Try using [...headerObj] or [...headerObj.entries()] to create a two-dimensional array that you can iterate through.

Alternatively, you can use [...headerObj.keys()] and [...headerObj.values()] to create a regular array for easier manipulation.

Answer №3

Here are a few updates to your code. Check out the changes here.

app = angular.module('testDemo', []);

app.controller('submitCtrl',function($scope) {
 $scope.header={};
 $scope.inputHeaders=[];

 $scope.addHeader = function() {

 $scope.inputHeaders.push($scope.header);
 $scope.header = {};
 $scope.header.key='';
 $scope.header.value='';

}

$scope.log=function(){
 //alert('in log');
 $scope.inputHeaders.forEach(function (key, value) {
 console.log(key, value);
});
}
});

HTML:

<body ng-controller='submitCtrl'>
<div >

<input type="text"  class="=form-control" ng-model="header.key" placeholder="Key">
<input type="text" class="=form-control" ng-model="header.value" placeholder="value">
<button class="btn btn-sucess" ng-click="addHeader()">Add</button>
<button class="btn btn-sucess" ng-click="log()">Log</button>
<div>
<ul class="list-group">
<li class="list-group-item" ng-repeat="header in inputHeaders">


 <!-- need to to work on this logic -->
 <div ng-show="inputHeaders.length>=1">
 <input type="text"   ng-model="header.value" />
 <input type="text"   ng-model="header.key" />
 </div>

</li>
</ul>            
</div>

</div>
</body>

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

Tips for concealing the cursor indefinitely in Typed JS

Is there a way to hide the cursor permanently in TypedJS so that it doesn't blink or show while typing? I've come across tutorials on hiding it after typing is complete, but not from the beginning. Any suggestions on how to achieve this? ...

Tips for decreasing the width of a Grid column in MUI React

I have a total of 8 columns. The first column should be the smallest to accommodate a checkbox and does not require much space. I attempted to adjust the xl, lg, md values to 0.5 but was unsuccessful. Is there an alternative method to change the width of t ...

The functionality of Bootstrap tabs is compromised when used within a modal dialog

I am encountering an issue while using Django and Bootstrap to implement nav-tabs within a modal that is displayed upon clicking a button. The problem lies in the fact that when a tab is clicked, its content does not appear. Below is a basic example: {% ...

Reduce the size of log messages in cypress

I am looking to shorten the cypress messages to a more concise string, for instance: Cypress log Transform to: -assert expected #buy-price-field to have value 17,169.00. Is there a way to achieve this? I have searched through the documentation but hav ...

Simply close by clicking outside using basic vanilla JavaScript

I have successfully implemented a menu that closes (removes the added class) when clicking outside the menu button area. Although it is working fine, I am unsure if my code is correct. My understanding is that the click outside functionality should only b ...

What is the best way to eliminate a particular element from an array produced using the .map() function in

I am experiencing an issue with my EventCell.tsx component. When a user clicks on the component, an event is created by adding an element to the components state. Subsequently, a list of Event.tsx components is rendered using the .map() method. The problem ...

What can be done to prevent function from being treated as instance members within a controller's scope?

When using angularJS 1.3, the following code snippet showcases the functionality: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="http ...

Tips for implementing personalized command buttons in Kendo Grid with AJAX request utilizing JavaScript

I am struggling with implementing custom command buttons in a Kendo grid that makes an AJAX call using JavaScript to call a web API post action with dynamic parameters (start, stop, restart) behind button clicks. datasource dataSource = new ken ...

Can you please identify the TypeScript type associated with the return value of the match() method in String prototype?

I need help with creating a Regex in JavaScript const pattern = /S(\d+)E(\d+)/; // identifying characters between "S" and "D" const result = 'SE01E09'.match(pattern); How should I declare the result variable? I have attempted various ...

Issues with image uploads in Node.js database storage

Trying to update an image using the put method is resulting in a 'filename' undefined error. Interestingly, the image updates successfully when editing without changing the image. The code snippet below shows the implementation: app.put('/a ...

Is it possible to extract the body from the post request using req.body.item?

After working with Express, I learned how to extract body data from a post request. Most examples showed that using req.body.item should retrieve the desired value for tasks like inserting into a table. However, in my case, I found that I couldn't ac ...

Tips for adding elements to an angular $scope.array?

Currently, I am facing an issue that I cannot seem to pinpoint (most likely due to my limited expertise in AngularJS). In my HTML file, I have a basic ng-repeat set up like this: <ul> <li ng-repeat="fot in fotografia"><img src="{{fot.path ...

Exploring the properties within a MongoDB document using mapping functionality

I am trying to retrieve data from a document using Node.js and encountering an issue where the map operator is returning data with similar names twice. I am wondering if I can use filter instead of map to address this problem. Here is the code I am using t ...

What is the proper way to add an object to an array within an object in TypeScript?

import {Schedule} from './schedule.model'; export class ScheduleService{ private schedules:Schedule[]=[ new Schedule("5:00","reading"), new Schedule("6:00","writing"), new Schedule("7:00","cleaning") ]; getSchedule(){ ret ...

How can I ensure that the size of the Dropdown Menu Item matches its parent in both Bootstrap and CSS styles?

I am working on a navigation bar that has a dropdown menu which appears on hover. I want the size of the dropdown menu items to match the size of the parent element. Here is an image for reference: https://i.stack.imgur.com/oNGmZ.png Currently, the "One ...

Adding new data to an object of objects can be a complex task, especially when the new data is coming from a state variable in React that is also an

I'm currently working on populating an object of objects with new data that is being stored in a state variable in React, which is also an object. Here's the code snippet I have: let userData = { harsh:{ password:"harsh", ema ...

What is the process for converting the output of cryptoJS.sha256 to binary in a Postman pre-request script?

Seeking assistance in creating an HMAC signature using a pre-request script in Postman. While troubleshooting, it has become apparent that there is an issue with the signature generation process. Although a proof of concept example provides expected result ...

Unable to assign value to Ref data property in Vue3 due to undefined item

Recently, I've been utilizing Vue3 and Nuxt3 to work on a project. My main task involves extracting the :id parameter from the URL and checking if it matches an ID in a JSON file. If there is a match, I update a reference data point called 'exist ...

Navigating the world of getElementById and addEventListener outside of the DOM

Having some dynamic HTML code in my JS, I'm hoping to assign an ID to a particular tag: content: ` <p id="openKeyboard"> If the click happens, I want to trigger an event. </p> ` However, upon ...

Ways to determine if an element is at the top of a page

I need help with a test case that involves checking if the title scrolls up to the top of the page when a button is clicked. The challenge is that there is a default header on the page, so the title should scroll below that. How can we verify this scenar ...