js根據相同屬性值將一個一維對象數組轉為二維數組



將一個一維對象數組,根據相同的屬性值,轉化成一個二維數組 

 

// 待轉換的一維數組 var arrayFirst = [{ code: 1, datas: 'a網吧' }, { code: 1, datas: 'b網吧' }, { code: 2, datas: 'a酒店' }, { code: 2, datas: 'b酒店' }, { code: 3, datas: 'a學校' }, { code: 3, datas: 'b學校' }, { code: 3, datas: 'c學校' } ] 

 

按照相同的code值轉換成二維數組

// 轉換后的二維數組 [ [{code: 1, datas: "a網吧"},{code: 1, datas: "b網吧"}], [{code: 2, datas: "a酒店"},{code: 2, datas: "b酒店"}], [{code: 3, datas: "a學校"},{code: 3, datas: "b學校"},{code: 3, datas: "c學校"}]] 

 

 

es6的方法

使用es6的方法
Object.values() //返回 值 數組
返回數組,成員是參數對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵值

// 轉換后的二維數組 var arrayTwo = Object.values(arrayFirst.reduce((res, item) => { res[item.code] ? res[item.code].push(item) : res[item.code] = [item]; return res; }, {})); console.log(arrayTwo) 

 

 

第二種方法

// 轉換后的二維數組 function convert (arr) { var map1 = {}; while(arr.length) { let current = arr.pop(); // 會影響原數組 map1[current.code] = map1[current.code] || []; map1[current.code].push(current); } return Object.keys(map1).map(key => map1[key]); } var arrayTwo = convert(arrayFirst) console.log(arrayTwo) 

 

 

順便介紹一下reduce 方法 :

array.reduce(function(total, currentValue, currentIndex, arr), initialValue) 

 

reduce() 方法接收一個函數作為累加器,數組中的每個值(從左到右)開始縮減,最終計算為一個值。
reduce() 對於空數組是不會執行回調函數的

參數 描述
total 必需。初始值, 或者計算結束后的返回值。
currentValue 必需。當前元素
currentIndex 可選。當前元素的索引
arr 可選。當前元素所屬的數組對象
initialValue 可選。傳遞給函數的初始值
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM