How js classifies and assembles array repeating elements into a tree structure

now the data is as follows:

var _arr = [{"area":"","name":""},{"area":"","name":""},{"area":"","name":""},{"area":"","name":""},{"area":"","name":""},{"area":"","name":""}];  

want to reassemble the data into

var _arr = [{"area":"","name":[""]},{"area":"","name":[""]},{"area":"","name":["",""]},{"area":"","name":["",""]}];  

that is, to judge the area. If the area is the same, put the name into the same array and find the method.


just use map

let m = {}
for(let i = 0; i< _arr.length; iPP){
    let t = _arr[i]
    if(!m[t.area]){
        m[t.area] = []
    }
    m[t.area].push(t.name)
}

let arr = []
for(let key in m){
    arr.push({ area: key, name: m[key] })
}

the idea of dealing with array and object data is very important, the general means is recursion, or with the help of the third variable to complete traversal, you can also use the principle of non-repetition of object key values to do a lot of things.

Menu