preface

Hi, I’m Wangly, a front-end food cat. Maps have been used for data structures in many recent projects. So summarize an article to review yourself. By the way, summarize the new data structure of ES6 for everyone. It is not used as much in development as Object. But using it in certain situations is a miracle. So today I gave you both the Map. If you don’t know what a Map is, try reading articles by other writers in Nuggets. Of course, it’s ok to just look at it.

If you feel good, you can click a “like” after watching it, and support the author.

What is the Map

Map is a new data structure added to ES6. It is a shareholder of Keyed Collections, which provides users with a more powerful set of key extensions. More free container privacy, such as set,get,size series of native apis, to facilitate user management of containers. Under certain circumstances, they can provide considerable performance benefits.

When to use Map instead of Object

  • The key of an Object cannot support the data
  • You need to know the size of the object
  • You don’t want conflicting keys
  • When you define a key value

I recommend reading this article to learn the basics: Front-end Smarts: When to use Maps instead of regular JS objects

Some common business scenarios

These are real business scenarios, very simple. Try this solution if you run into it on your project. I will take VUE as a demonstration environment to give you a detailed Demo. Friends in other environments learn from ideas oh. The following three cases can all be implemented with Object. It’s just a little weird to write.

Scenario 1: Personal information table

In some Admin projects, we usually display personal information, such as displaying the following information on the page, what do you do? All of a sudden a bad way to write it.


<div class="info-item">
  <span>The name</span>
  <span>{{info.name}}</span>
</div>
<div class="info-item">
 <span>age</span>  <span>{{info.age}}</span> </div> <div class="info-item">  <span>gender</span>  <span>{{info.sex}}</span> </div> <div class="info-item">  <span>Mobile phone no.</span>  <span>{{info.phone}}</span> </div> <div class="info-item">  <span>Home address</span>  <span>{{info.address}}</span> </div> <div class="info-item">  <span>Home address</span>  <span>{{info.duty}}</span> </div>  </div> Copy the code
mounted() {
  this.info = {
    name: 'wangly'.    sex: 'male'.    age: '18'. phone: '13000000000'. address: 'China... '. duty: 'General Manager'  } } Copy the code

We transform it through Map, save the label and value we need to display in our Map and render it to the page. Although in javascript the code looks precipitated. It’s just a demonstration. Specific operation we can think together. How to solve it better. This is just my opinion. Although the logic layer code more. But the View saves a lot of coupling code. So ah is my simple understanding of the cell. Do you have a better solution?

<template>
  <div id="app">
    <! -- <router-view></router-view> -->
    <div class="info-item" v-for="[label, value] in infoMap" :key="value">
      <span>{{label}}</span>
 <span>{{value}}</span>  </div>  </div> </template> Copy the code
data: (a)= > ({
  info: {},
  infoMap: {}
}),
mounted () {
 this.info = {  name: 'wangly'. sex: 'male'. age: '18'. phone: '13000000000'. address: 'China... '. duty: 'General Manager'  }  const mapKeys = ['name'.'gender'.'age'.'phone'.'Home Address'.'identity']  const result = new Map(a) let i = 0  for (const key in this.info) {  result.set(mapKeys[i], this.info[key])  i++  }  this.infoMap = result } Copy the code

So how do you render to the page?

Map also becomes very realistic under V-FOR. Take a look at the following code. Step out

<! -- show map --><div class="info-item" v-for="[label, value] in infoMap" :key="value">
  <span>{{label}}</span>
  <span>{{value}}</span>
</div>
Copy the code


Conversations,

Through the map traversal, after deconstructing the desired key and value, you can display some complete key pairs on the page. This is a place I use a lot. Of course, it can also be done by calculating attributes.

Scenario 2: Customizing the submission form

I don’t know if you’ve ever touched front-end dynamic forms. This means a form that is composed. Such as:

  • Form A field: [‘A’, ‘B’, ‘C’, D, ‘E’]
  • B Form field: [‘A’, ‘C’, D, ‘E’]
  • C Form fields: [‘A’, ‘B’, D, ‘E’, ‘F’]

It varies depending on the form being uploaded in different situations. If you want to render to the page, it is easy to have blank columns. Because it has no data, you don’t know what your current form looks like. Basic scenario: Epidemic questionnaires for students, teachers and staff, they are not the same. They all need to be handed over to someone who’s in charge of this. So the staff view the form information is diversified. You have multiple templates. You even need to do an export XLS file. Therefore, traditional forms prop is difficult to adapt to this diverse thing.

The template structure

List objects are different. This should be done first with the fields they pass up the table. We need to render to the page by label, value.

A template:

The template 2:

The dynamic form

Results 1:

The results of 2:

The implementation process

Set (child.label, child.value) converts the template array into a map. In this way, we should not pay too much attention to some template fields. You can focus on rendering data.

<table class="table" border="1" id="table"> <tr> // Obtain header, i.e. map key <th v-for="([label], key) in tablemap.length > 0? tableMap[0] : [] "> {{label}} < / th > < / tr > < tr / / render the map array v - for =" (map, index) in tableMap"> <td v-for="[,value] in map">{{value}}</td> </tr> </table>Copy the code
createModule () {
  this.tableMap = []
  this.tableList.forEach(el= > {
    const map = new Map(a)    map.set('time', el.name)
 el.custom.forEach(child= > {  // Label as key and value as value  map.set(child.label, child.value)  })  / / end of the map  this.tableMap.push(map)  }) } Copy the code

Scenario 3: Avoid duplicate data

The most common place for dynamic updates is for more pull-down loading on mobile. Normally you can’t make a mistake. But there is one very special case. The accumulated content that the socket pushes in real time. We all know that the socket has a communication delay when sending messages. There are many influences on this aspect. There is often no guarantee that the user will manually update the message content when the socket receives the object added to the DOM. If the list exists. When you dynamically add socket.onMessage to the list, there will be value conflicts. Although you can filter it out. But keys that pass through the map have no repeatability. I can do this very well.

Before and after button is added



As you can see, a new TAB 9 appears on the page. But the browser reported a duplicate error key. becausev-forI’m using id askeyThere are two identical data in the view, which is not reasonable phenomenon. If we use Map, we don’t have to worry about this at all. We have no mattersetHow many times can the same data affect the repetitionkeyThe newkeyIt replaces old data. The oldThe new

<div class="info-item" v-for="[key, {id, label}] in tableMap" :key="key">
  <span>{{id}}</span>
  <span>{{label}}</span>
</div>
<button @click="pushTable">Add label 9</button>
 Copy the code
// @ pushTbale function 
pushTable () {
  this.tableMap.set(9, {
    id: 9.    label: 'label 10'
 })  this.tableMap = new Map(this.tableMap) },  // createData @moount function const map = new Map(a)for (let index = 0; index < 10; index++) {  map.set(index, {  id: index,  label: ` label${index}`. }) } this.tableMap = map  Copy the code

tips

  • Vue responds poorly to maps when you directlysetThe data is updated. However, the observer cannot be notified to update the view. When you need to respond to updates, only passively reset the current wholeMapThis is actually unreasonable.
  • Map and Object are two different things. Map can do things that Object sometimes can’t.
  • Use Map wisely and think about whether you need it.
  • Don’t get stuck in a single principle, think about whether there is a better way to solve the problem. (Div is everywhere, object is a trick)
  • The Map usage scenario is small, but don’t ignore it.

After the speech

Give me a thumbs up if you think it helps. Your support is the best affirmation for me. Individual other articles recommended. Content is not necessarily the best solution.

V-model source code analysis: click the jump front may by: click the jump