后台返回对象数组,对象属性相同时,只取一个对象
Posted CNundefined
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了后台返回对象数组,对象属性相同时,只取一个对象相关的知识,希望对你有一定的参考价值。
后台返回的数据:
[ {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 }
以上是关于后台返回对象数组,对象属性相同时,只取一个对象的主要内容,如果未能解决你的问题,请参考以下文章