Example of converting JS one-dimensional array into three-dimensional array

Example of converting JS one-dimensional array into three-dimensional array

Today I saw a friend asking a question in the Q&A section of CSDN. He wanted to convert a one-dimensional array into a three-dimensional array. I was not very busy, so I immediately arranged a task for him. Of course, I didn’t bother to look up any information or anything. I just followed my own ideas! There is source code below

insert image description here

The above is his data format, and the following is the data format to be converted

insert image description here

Without further ado, let’s get straight to the code

 let arr = [{
      'peovince': 'a', 'city': 'b', 'area': 'c'
    },
    {
      'peovince': 'a', 'city': 'b', 'area': 'd'
    },
    {
      'peovince': 'a', 'city': 'e', ​​'area': 'f'
    },
    {
      'peovince': 'a', 'city': 'e', ​​'area': 'g'
    },
    {
      'peovince': 'o', 'city': 'p', 'area': 'q'
    },
    {
      'peovince': 'o', 'city': 'p', 'area': 'r'
    },
    {
      'peovince': 'o', 'city': 's', 'area': 't'
    },
    {
      'peovince': 'o', 'city': 's', 'area': 'v'
    }];

Start converting

let list = Array.from(new Set(
      arr.map(item => {
        return item['peovince']
      })))
    let subList = []
    list.forEach(res => {
      arr.forEach(ele => {
        if (ele['peovince'] === res) {
          let nameArr = subList.map(item => item.value)
          if (nameArr.indexOf(res) !== -1) {
            let nameArr2 = subList[nameArr.indexOf(res)].children.map(item => item.value)
            if (nameArr2.indexOf(ele['city']) !== -1) {
              subList[nameArr.indexOf(res)].children[nameArr2.indexOf(ele['city'])].children.push({
                value: ele['area'],
                label:ele['area'],
              })
            } else {
              subList[nameArr.indexOf(res)].children.push({
                value: ele['city'],
                label:ele['city'],
                children: [{
                  value: ele['area'],
                  label:ele['area'],
                }]
              })
            }
          } else {
            subList.push({
              value: res,
              label: res,
              children: [{
                value: ele['city'],
                label:ele['city'],
                children: [{
                  value: ele['area'],
                  label:ele['area'],
                }]
              }]
            })
          }
        }
      })

    })
    console.log(subList)

The subList printed at the end is the desired format. Let's take a look at the printing

ps: JavaScript one-dimensional array to two-dimensional array

The first case: when the array contains strings

  let array = [1, 2, 3, 4, 5, 6, 7, 8];
  len len = array.length;
  let n = 4; //Assume that 4 items are displayed per line let lineNum = len % n === 0 ? len / n : Math.floor( (len / n) + 1 );
  let res = [];
  for (let i = 0; i < lineNum; i++) {
    // The slice() method returns a shallow copy of a portion of an array selected from the beginning to the end (excluding the end) into a new array object. The original array will not be modified.
    let temp = array.slice(i*n, i*n+n);
    res.push(temp);
  }
  console.log(res);

The second case: when the array contains objects

When the array elements are objects, you cannot use the slice method to intercept them, because slice is a shallow copy. The resulting problem is that if you modify the value of the newly generated array object, it will affect the value of the object in the original array.
Here we introduce a method using JSON.stringify and JSON.parse.

  let objArray = [{a: 1}, {b: 2}, {c: 3}, {d: 4}, {e: 5}, {f: 6}, {g: 7}];
  let len ​​= objArray.length;
  let n = 4; //Assume that 4 items are displayed per line let lineNum = len % 4 === 0 ? len / 4 : Math.floor( (len / 4) + 1 );
  let res = [];
  for (let i = 0; i < lineNum; i++) {
    let temp = objArray.slice(i*n, i*n+n);
    res.push(JSON.parse(JSON.stringify(temp)));
  }
  console.log(res);


This is the end of this article about converting JS one-dimensional array into three-dimensional array. For more relevant content about converting JS one-dimensional array into three-dimensional array, please search previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JS one-dimensional array converted to three-dimensional array method

<<:  MySQL detailed summary of commonly used functions

>>:  Method of iframe adaptation in web responsive layout

Recommend

Detailed explanation of the installation steps of the MySQL decompressed version

1. Go to the official website: D:\mysql-5.7.21-wi...

Three ways to share component logic in React

Without further ado, these three methods are: ren...

Solution to the problem of invalid width setting for label and span

By default, setting width for label and span is in...

Create a screen recording function with JS

OBS studio is cool, but JavaScript is cooler. Now...

Detailed explanation of keepAlive use cases in Vue

In development, it is often necessary to cache th...

JavaScript to implement login slider verification

This article example shares the specific code of ...

Nginx uses ctx to realize data sharing and context modification functions

Environment: init_worker_by_lua, set_by_lua, rewr...

How to configure jdk environment under Linux

1. Go to the official website to download the jdk...

The meaning of the 5 types of spaces in HTML

HTML provides five space entities with different ...

Practical record of solving MySQL deep paging problem

Table of contents Preface Why does limit deep pag...

Vue gets token to implement token login sample code

The idea of ​​using token for login verification ...

The first step in getting started with MySQL database is to create a table

Create a database Right click - Create a new data...

The complete process of Docker image creation

Table of contents Preface Creation steps Create a...