問題描述:
一個數組對象,提取key 值相同的為一個數組。
===>
解決思路:
首先確定,數組中key 不相同的一共有多少個(可以用數組對象去重)
然后,建立一個二維數組,數組的長度去重之后數組的長度
最后,將key 相同的放在二維數組里面的數組中
解決辦法:
var arr1 = [ { id: 1, type: 'qw' }, { id: 2, type: 'qw' }, { id: 1, type: 'qw2' }, { id: 3, type: 'qw111' }, { id: 3, type: 'qw222' }, { id: 3, type: 'qw333' } ] const s = new Set() arr1.forEach(item => { s.add(item.id) }) // ===> 根據Set 的size 屬性 用來獲取不重復的數據有多少個 console.log(s, 'sss') const newData = Array.from( // ====> 這一步很重要,要確定二維數組的長度是多少 { length: s.size }, () => [] ) console.log(newData, '信數組') arr1.forEach(item => { const index = [...s].indexOf(item.id) // ====> 循環原數組,將key相同的對象提取到二維數組中 newData[index].push(item) }) newData.forEach((item) => { item[0].children = [] item.forEach((ele, index, array) => { if (index > 0) { array[0].children.push(ele) } }) item.splice(1) }) console.log(newData, '數組數組') // 打印之后則為下面形式 // var array = [ // [ // { id: 1, type: 'qw' }, // { id: 1, type: 'qw' } // ], // [ // { id: 2, type: 'qw2' } // ], // [ // { id: 3, type: 'qw111' }, // { id: 3, type: 'qw222' }, // { id: 3, type: 'qw333' } // ] // ]