后台返回对象数组,对象属性相同时,只取一个对象
后台返回的数据:
[ {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 }
posted on 2017-06-08 13:14 CNundefined 阅读(434) 评论(0) 编辑 收藏 举报