JS--陣列物件合併

純純憨憨發表於2019-04-15

這個題目是一道筆試題,當時沒有去寫,因為沒有什麼思路,後來自己回想了一下,準備做一下

題目是這個樣子的

陣列合並:

源陣列:[{
            teacher:'a',
            student:'Lily',
            age:20
        },{
            teacher:'a',
            student:'Lucy',
            age:22
        },{
            teacher:'a',
            student:'Meimei',
            age:22
        },{
            teacher:'b',
            student:'Sudy',
            age:21
        },{
            teacher:'b',
            student:'LeiLei',
            age:18
        }];

目標陣列: [{
            teacher:'a',
            students:[{
               student:'Lily',
                age:20 
            },{
               student:'Lucy',
                age:22 
            },{
               student:'Meimei',
                age:22 
            }]
        },{
            teacher:'b',
            students:[{
               student:'Sudy',
                age:21 
            },{
               student:'LeiLei',
                age:18 
            }]
        }]複製程式碼



我的解答思路如下:

//源陣列
        let arr = [{
            teacher:'a',
            student:'Lily',
            age:20
        },{
            teacher:'a',
            student:'Lucy',
            age:22
        },{
            teacher:'a',
            student:'Meimei',
            age:22
        },{
            teacher:'b',
            student:'Sudy',
            age:21
        },{
            teacher:'b',
            student:'LeiLei',
            age:18
        }];
        //先把源陣列變成目標陣列的形式
        let arrData = [];
        arr.forEach((item) => {
         let arrObj = {
            teacher:item.teacher,
            students:[]
         };
         let studentsArr = {
            student:item.student,
            age:item.age
         };
         arrObj.students.push(studentsArr);
         arrData.push(arrObj);
        })
        console.log(arrData,'-----------');
        /**
         * 先去重,後合併
         * 1、把轉化後的目標陣列規進行去重
         * 2、把去重後的資料和轉化後的目標陣列中相同teacher的資料合併students
        */
       let newArr = [];
       let newObj = {};
       arrData.forEach((item,index) => {
         if (!newObj[item.teacher]) {
            newArr.push(item);
            newObj[item.teacher] = true;
          } else {
            newArr.forEach(el => {
              if (el.teacher === item.teacher) {
                // el.students = el.students.concat(item.students);
                el.students = [...el.students, ...item.students]; // es6語法
              }
            })
          }
       })複製程式碼

輸出的結果:

JS--陣列物件合併



望大家給更多的解答思路以及方法!



相關文章