需求:按照後臺返回的陣列的順序,和返回的物件的鍵值合成新的物件,便於渲染到頁面上
let obj={
'213_tsxRaXuUEMXLEFWkp4bwKL': "2019-02-26",
'2771_CGeEeRyBRdWWkK3ZAvGAWo': "充足",
'5451_BMkcv5nT9XK2g6QBFjqYuH': ["測試部"],
'6725_gNSy4ksbBGhVAhYdurThJL': "管理員",
'7937_Sg4nvPG7qVrwrFwoBHexcj': "",
'9166_yL68EB3pCT3DcZMD4QxR26': ''
};//後臺返回的鍵值對物件
複製程式碼
//需要按照此陣列順序
let obj1=["213_tsxRaXuUEMXLEFWkp4bwKL",
"6725_gNSy4ksbBGhVAhYdurThJL",
"5451_BMkcv5nT9XK2g6QBFjqYuH",
"2771_CGeEeRyBRdWWkK3ZAvGAWo" ,
"7937_Sg4nvPG7qVrwrFwoBHexcj",
"9166_yL68EB3pCT3DcZMD4QxR26"]
複製程式碼
//根據上面obj1的順序取出dname,結合obj的鍵值合成新的物件
let info={
'213_tsxRaXuUEMXLEFWkp4bwKL': {dname: "填寫日期", field_id: "213_tsxRaXuUEMXLEFWkp4bwKL", id: "213_tsxRaXuUEMXLEFWkp4bwKL", dfield: "f5"},
'2771_CGeEeRyBRdWWkK3ZAvGAWo': {dname: "今日完成工作", field_id: "2771_CGeEeRyBRdWWkK3ZAvGAWo", id: "2771_CGeEeRyBRdWWkK3ZAvGAWo",dfield: "f8"},
'6725_gNSy4ksbBGhVAhYdurThJL': {dname: "填寫人", field_id: "6725_gNSy4ksbBGhVAhYdurThJL", id: "6725_gNSy4ksbBGhVAhYdurThJL",dfield: "f6"},
'7937_Sg4nvPG7qVrwrFwoBHexcj': {dname: "未完成工作", field_id: "7937_Sg4nvPG7qVrwrFwoBHexcj", id: "7937_Sg4nvPG7qVrwrFwoBHexcj",dfield: "f9"},
'9166_yL68EB3pCT3DcZMD4QxR26': {dname: "備註", field_id: "9166_yL68EB3pCT3DcZMD4QxR26", id: "9166_yL68EB3pCT3DcZMD4QxR26",dfield: "f10"},
'5451_BMkcv5nT9XK2g6QBFjqYuH': {dname: "所在部門", field_id: "5451_BMkcv5nT9XK2g6QBFjqYuH", id: "5451_BMkcv5nT9XK2g6QBFjqYuH",dfield: "f7"}
}
,
複製程式碼
解決方法:(哈哈,就是二次遍歷,但是遍歷的順序要注意,才接觸,所以不懂得可以試試反過來遍歷,看到問題就長記性了)
1、先遍歷obj1,因為是按照obj1的順序
2、obj1裡遍歷obj物件
3、判斷obj的第i個鍵名是否和obj1[j]相等
4、在判斷裡組合自己想要的資料結構
let arr = [];
for(let j=0;j<obj1.length;j++){
for (let i in obj){
let obj2={}
console.log('是否obj1[j]==i相等',j,obj1[j]==i)
if(obj1[j]==i){
obj2.name=info[i].dname;
obj2.value=obj[i];
console.log('obj2 ',obj2)
arr.push(obj2)
}
}
}
console.log('arr ',arr)
複製程式碼