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

Linux file system operation implementation

This reading note mainly records the operations r...

How to achieve the maximum number of connections in mysql

Table of contents What is the reason for the sudd...

Import csv file into mysql using navicat

This article shares the specific code for importi...

Write a mysql data backup script using shell

Ideas It's actually very simple Write a shell...

Three ways to implement text color gradient in CSS

In the process of web front-end development, UI d...

Example code for implementing a hollow mask layer with CSS

Contents of this article: Page hollow mask layer,...

JavaScript canvas implements moving the ball following the mouse

This article example shares the specific code of ...

jQuery realizes the sliding effect of drop-down menu

When we make a web page, sometimes we want to hav...

Solution for FileZilla 425 Unable to connect to FTP (Alibaba Cloud Server)

Alibaba Cloud Server cannot connect to FTP FileZi...

In-depth analysis of MySQL explain usage and results

Preface In daily work, we sometimes run slow quer...

Windows 10 is too difficult to use. How to customize your Ubuntu?

Author | Editor Awen | Produced by Tu Min | CSDN ...

How to install JDK8 on Windows

1. Download: http://www.oracle.com/technetwork/ja...