数组对象,提取key值相同的为同一数组


问题描述:

一个数组对象,提取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' }
    //   ]
    // ]

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM