Array Mapping in AngularJS

Muhammad Adil Mar 20, 2022
  1. Array Mapping in AngularJS
  2. Map Entries
  3. Steps for Array Mapping in AngularJS
Array Mapping in AngularJS

This article will deal with Array Mapping in AngularJS.

Array Mapping in AngularJS

Array mapping is one of the most valuable features in AngularJS. It allows you to create variables on a single line, saving you from declaring each variable separately.

It simplifies data binding, improves performance, and allows us to create more maintainable templates. Moreover, the reader can easily understand what values are assigned and the variable’s purpose in your code.

Array mapping is done using the map function and passing the array as a parameter along with other parameters like a key, value, etc.

Syntax:

var myArr = map(myObj);
//myArr = [{key1: "value1", key2: "value2"}, {key3: "value3"}];

Map Entries

Below are the map entries we can use.

  • map.delete() discards an item from the map.
  • map.size() returns the map’s size.
  • map.clear() removes the map data.
  • map.set() adds new entries.
  • map.get() retrieves an entry from map.
  • map.has() determines whether or not an entry in the map exists.

Steps for Array Mapping in AngularJS

The following steps will help you with array mapping in AngularJS:

  • Create a controller for the page.
  • Create an array of data.
  • Add a table to the page and set it up with columns and rows.
  • Add code to the controller that loops through each row of data and creates an input field for each column.
  • Create an object literal.
  • Assign values to each key of the object literal by using brackets [].
  • Create a map function that assigns values from the object literal to our array.

Example of Array Mapping in AngularJS

Let’s see an example of Angular array mapping.

var tags =  [{ "id": 1, "name": "Adil" }, { "id": 2, "name": "Steve" }, { "id": 3, "name": "Roman" }, { "id": 4, "name": "John" }]
var selectedTags = [1,2,3];
var tagMap = tags.reduce(function(map, tag) {
    map[tag.id] = tag.name;
    return map;
}, {});
var selectedArray = selectedTags.map(function(id) {
    return tagMap[id];
});
console.log(selectedArray);

Click here to check the live demonstration of the code as mentioned above.

Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook

Related Article - Angular Array