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

10 Best Practices for Building and Maintaining Large-Scale Vue.js Projects

Table of contents 1. Use slots to make components...

MySQL transaction autocommit automatic commit operation

The default operating mode of MySQL is autocommit...

Demystifying the HTML 5 Working Draft

The World Wide Web Consortium (W3C) has released a...

HTML elements (tags) and their usage

a : Indicates the starting or destination positio...

Understand the basics of Navicat for MySQL in one article

Table of contents 1. Database Operation 2. Data T...

How to set Nginx log printing post request parameters

【Foreword】 The SMS function of our project is to ...

Should I use Bootstrap or jQuery Mobile for mobile web wap

Solving the problem Bootstrap is a CSS framework ...

Example of using js to natively implement year carousel selection effect

Preface Use js to achieve a year rotation selecti...

Using CSS3 to achieve transition and animation effects

Why should we use CSS animation to replace JS ani...

Vue component library ElementUI realizes the paging effect of table list

ElementUI implements the table list paging effect...

HTML table tag tutorial (45): table body tag

The <tbody> tag is used to define the style...

Native JavaScript to achieve slide effects

When we create a page, especially a homepage, we ...

Ubuntu 20.04 sets a static IP address (including different versions)

Because Ubuntu 20.04 manages the network through ...