JS uses map to integrate double arrays

JS uses map to integrate double arrays

Preface

Recently, due to the company's business needs, we wrote ECharts charts to display the changes in data related to the company's phased business. The server needs to query the data and return it to the front end for data display. However, since the returned data is not convenient for the front-end ECharts to display, data integration is required. However, due to my lack of experience, I can only ask the company's boss for help. With the help of the boss, I completed the data integration and learned an unprecedented merging method to share with you today.

Simulating data

The following figure shows the two arrays to be merged.

Merged data

The merged data requires that the objects in the double array be merged with time as the only key. If the value in the object exists, it will be displayed. If not, the key that the object does not have will be initialized and the initial value will be 0 (if the expression is not clear, the final merged data is shown below)

Merger ideas

The js mapp technology is used in this merger. Since time is the only key, we need to traverse array 1 to initialize a map with time as the key, then traverse array 2 to complement the data, and then convert the processed map into an array.

Code display & analysis

first step

First declare the simulation data and create an empty object to carry the map

      //Simulated data arr1
      let testArrOne = [
        { date: "2021-8-11", testNumOne: 1 },
        { date: "2021-8-12", testNumOne: 2 },
        { date: "2021-8-13", testNumOne: 3 },
      ];
      //Simulated data arr2
      let testArrTwo = [
        { date: "2021-8-12", testNumTwo: 2 },
        { date: "2021-8-14", testNumTwo: 4 },
        { date: "2021-8-15", testNumTwo: 5 },
      ];
      //Merge method let testMap = {}; //First declare an empty object as a map

Step 2

Traverse the array to initialize the map

   //Traverse the first array testArrOne.forEach((item) => {
        testMap[item.date] = {
          date: item.date, //initialization time testNumOne: item.testNumOne || 0, //initialization test data one testNumTwo: 0, //initialization test data two };
      });
  

Then we get a map with time as the only key. We print the following data

Step 3

Traverse array 2 to perform related assignment and initialization operations

    //Traverse the second array testArrTwo.forEach((item) => {
       //If the array contains a map object containing time, copy it. If a new time is found, initialize and assign an empty object testMap[item.date] = testMap[item.date] || {}; 
       //Assignment timetestMap[item.date].date = item.date;
        //Assign test data one. If not, initialize testMap[item.date].testNumOne = testMap[item.date].testNumOne || 0;
        //Auxiliary test data twotestMap[item.date].testNumTwo = item.testNumTwo;
      });

Print the map to get the integrated object as follows

Step 4

Convert map to arr and you are done.

 this.listMapUtils.map2List(testMap);

The following is the encapsulated code for converting between map and arr

      listMapUtils: {
      //arr to map method list2Map: function(list, key) {
          let map = {};
          if (list && Array.isArray(list) && list.length > 0) {
            list.forEach((item) => {
              item[key] ? (map[item[key]] = item) : "";
            });
          }
          return map;
        },
        //map to arr method map2List: function(map) {
          let list = [];
          if (map && typeof map === "object") {
            for (let key in map) {
              list.push(map[key]);
            }
          }
          return list;
        },
      },


Full code

Because it is convenient to show the method of converting between map and arr, I have stated it in the data. Students should not write it like this. As a front-end, you still need to have a modular idea.

<template>
  <div></div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      listMapUtils: {
        list2Map: function(list, key) {
          let map = {};
          if (list && Array.isArray(list) && list.length > 0) {
            list.forEach((item) => {
              item[key] ? (map[item[key]] = item) : "";
            });
          }
          return map;
        },
        map2List: function(map) {
          let list = [];
          if (map && typeof map === "object") {
            for (let key in map) {
              list.push(map[key]);
            }
          }
          return list;
        },
      },
    };
  },
  created() {
    this.mergeArr();
  },
  methods: {
    mergeArr() {
      //Simulated data arr1
      let testArrOne = [
        { date: "2021-8-11", testNumOne: 1 },
        { date: "2021-8-12", testNumOne: 2 },
        { date: "2021-8-13", testNumOne: 3 },
      ];
      //Simulated data arr2
      let testArrTwo = [
        { date: "2021-8-12", testNumTwo: 2 },
        { date: "2021-8-14", testNumTwo: 4 },
        { date: "2021-8-15", testNumTwo: 5 },
      ];

      //Merge method let testMap = {}; //First declare an empty object as a map

      //Traverse the first array testArrOne.forEach((item) => {
        testMap[item.date] = {
          date: item.date,
          testNumOne: item.testNumOne || 0,
          testNumTwo: 0,
        };
      });

      testArrTwo.forEach((item) => {
        testMap[item.date] = testMap[item.date] || {}; //Initialize the object testMap[item.date].date = item.date;
        testMap[item.date].testNumOne = testMap[item.date].testNumOne || 0;
        testMap[item.date].testNumTwo = item.testNumTwo;
      });
      
      //map to arr
      this.listMapUtils.map2List(testMap);
      //Get the final result console.log(this.listMapUtils.map2List(testMap));
    },
  },
};
</script>

<style></style>

Summarize

This is the end of this article about JS using map to integrate double arrays. For more relevant JS integration double array content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript tips to help you improve your coding skills
  • Sharing some tips on JavaScript
  • 9 JavaScript daily development tips
  • JavaScript Coding Tips Sharing
  • Tips for numerical calculations in JavaScript front-end development
  • Let you master 9 JavaScript tips in 5 minutes
  • JS 4 super practical tips to improve development efficiency

<<:  Installation of various versions of MySQL 8.0.18 and problems encountered during installation (essence summary)

>>:  Install Jenkins with Docker and solve the problem of initial plugin installation failure

Recommend

About the role of meta in HTML (collected and sorted from the Internet)

W3Cschool explains it this way The <meta> el...

Practical experience of implementing nginx to forward requests based on URL

Preface Because this is a distributed file system...

Share the 15 best HTML/CSS design and development frameworks

Professional web design is complex and time-consu...

MySQL database operations (create, select, delete)

MySQL Create Database After logging into the MySQ...

PyTorch development environment installation tutorial under Windows

Anaconda Installation Anaconda is a software pack...

How to add ansible service in alpine image

Use apk add ansible to add the ansible service to...

Detailed explanation of Linux text processing command sort

sort Sort the contents of a text file Usage: sort...

Ant designing vue table to achieve a complete example of scalable columns

Perfect solution to the scalable column problem o...

Causes and solutions to the garbled character set problem in MySQL database

Preface Sometimes when we view database data, we ...

Linux debugging tools that developers and operators must look at [Recommended]

System performance expert Brendan D. Gregg update...

Interviewers often ask questions about React's life cycle

React Lifecycle Two pictures to help you understa...

Detailed explanation of the use of Docker commit

Sometimes you need to install certain dependencie...

Modify the maximum number of mysql connections and configuration files in docker

1. Find the mysql image docker ps 2. Enter the mi...