1. 程式人生 > >後臺返回對象數組,對象屬性相同時,只取一個對象

後臺返回對象數組,對象屬性相同時,只取一個對象

元素 屬性 con als bsp class total code log

後臺返回的數據:

[
  {confirmCharge: "0.00", orderId: "--", changeId: "1", realName: "王五", totalConfirmCharge: "0.00",…},
  {confirmCharge: "0.00", orderId: "288783482594267136", changeId: "", realName: "王五",…},
  {confirmCharge: "0.00", orderId: "--", changeId: "1", realName: "王五", totalConfirmCharge: "0.00",…},
  {1: 1, totalOrderTimes: 2}
]

要求:

changeId相同的項,只取一條數據,changeId為空,原樣取出,最後一條數據不取

目標數據:

[
  {confirmCharge: "0.00", orderId: "--", changeId: "1", realName: "王五", totalConfirmCharge: "0.00",…},
  {confirmCharge: "0.00", orderId: "288783482594267136", changeId: "", realName: "王五",…}
]

思路:

把changeId屬性值存到一個arr數組,存目標數據前將每一項的changeId和arr中的值進行對比,如果相同,就不取該項

實現代碼:

var arr = [],ifContain 
var objArr = [
  {confirmCharge: "0.00", orderId: "--", changeId: "1", realName: "王五", totalConfirmCharge: "0.00",…},
  {confirmCharge: "0.00", orderId: "288783482594267136", changeId: "", realName: "王五",…},
  {confirmCharge: "0.00", orderId: "--", changeId: "1", realName: "王五", totalConfirmCharge: "0.00",…},
  {
1: 1, totalOrderTimes: 2} ] var newArr = [] // console.log(arr) // arr用來存儲changeId ifContain用來判斷當前元素中的changId是否在arr中 newArr.push(objArr[0]) if(objArr[0].changeId){ arr.push(objArr[0].changeId) } for(var i=1;i<objArr.length-1;i++){ if(!objArr[i].changeId){ newArr.push(objArr[i]) }if(objArr[i].changeId){ ifContain = contains(arr,objArr[i].changeId) if(!ifContain){ newArr.push(objArr[i]) arr.push(objArr[i].changeId) } } } // JS判斷元素是否在數組內的實現代碼 contains(arr,obj) { let length = arr.length while(length--){ if(arr[length] === obj){ return true } } return false }

後臺返回對象數組,對象屬性相同時,只取一個對象