How to realize reordering of nested arrays by js
This article mainly introduces the relevant knowledge of "how to achieve nested array reordering in js". The editor shows you the operation process through an actual case. The method of operation is simple and fast, and it is practical. I hope this article "how to achieve nested array reordering in js" can help you solve the problem.
There are a total of two problems:
1. The problem of for loop outputting the same variable value in JS.
The js event handler does not run when the thread is idle, causing the last run time to output the last value of I.
Solution: declare this.content1 = {} in the loop
2. The sorting algorithm makes an error after the serial number is up to 10.
Solution: do not pay attention to string and int, the original data is string
Original data:
Goal: merge table, text, image into one content and sort by blockNO
Code:
Export default {data () {return {data: [], content1: {}, created () {this.test ()}, methods: {async test () {const {data: res} = await this.$http.get ('test1') for (let I = 0; I
< res.length; i++) { this.data1 = {} this.data1.name = res[i].name this.data1.blockNO = res[i].blockNO this.data1.class = res[i].class this.data1.id = res[i].id this.data1.children = [] this.data1.content = [] if (res[i].text) { for (let j = 0; j < res[i].text.length; j++) { this.content1 = {} this.content1.blockNO = res[i].text[j].blockNO this.content1.type = 'text' this.content1.detail = res[i].text[j].text this.data1.content.push(this.content1) } } if (res[i].table) { for (let j = 0; j < res[i].table.length; j++) { this.content1 = {} this.content1.blockNO = res[i].table[j].blockNO this.content1.type = 'table' this.content1.detail = res[i].table[j].table this.data1.content.push(this.content1) } } if (res[i].image) { for (let j = 0; j < res[i].image.length; j++) { this.content1 = {} this.content1.blockNO = res[i].image[j].blockNO this.content1.type = 'image' this.content1.detail = res[i].image[j].image this.data1.content.push(this.content1) } } for (let j = 1; j < this.data1.content.length; j++) { for (let i = 0; i < this.data1.content.length - j; i++) { if ( parseInt(this.data1.content[i].blockNO) >ParseInt (this.data1.content [I + 1] .blockno) {let tempnum = this.data1.content [I + 1] this.data1.content [I + 1] = this.data1.content [I] this.data1.content [I] = tempnum} this.data.push (this.data1) } console.log (this.data)} this is the end of the introduction to "how to reorder nested arrays by js". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.