使用js陣列map方法對老程式碼進行優化
阿新 • • 發佈:2020-12-29
技術標籤:JSjavascript
功能描述
將途中人員列表(optlList)中的id(id1;id2;id3)顯示人員的名稱,顯示成比如:李四,張三,王二,其中userList是已經查詢出來的人員集合,
1、原JS:
function(response){ for(var i=0; i<response.data.length; i++){ if(response.data[i].optlList != null){ if(response.data[i].optlList.indexOf(";") == -1){ for(var j=0; j<userList.length; j++){ if(userList[j].id == response.data[i].optlList){ response.data[i].optlList = userList[j].name; } } }else{ var nameList = ""; var dataList = response.data[i].optlLst.indexOf(";"); for(var k=0; k<dataList.length; k++){ for(var j=0; j<userList.length; j++){ if(userList(j).id == dataList(k)){ nameList = userList[j].name+','+nameList; continue; } } } response.data[i].optlList = nameList; } } } }
2、優化後js
function(response){ return response.data.map( //對集合進行map對映,以返回處理好後的集合 function(item){ //此函式的引數就是map對映的集合的元素 let nameList = []; if(item.optlList != null){ nameList = item.optlList.split(";").map( //對元素的optList按照";"進行拆分成一個新的集合,對新的集合進行map對映,對映處理後返回使用者name的集合 //對新集合map對映後的元素進行處理,其中userList.find(user => user.id == e)找到一個符合條件的元素即user,然後取出name組成name集合 e => userList.find(user => user.id == e).name ); } item.optlList = nameList.toString(); //對name集合處理成以","隔開的字串,如果想處理成其他符合隔開的字串用join,比如nameList.join(";")用分號隔開的字串 return item; } ) }