• 后台返回对象数组,对象属性相同时,只取一个对象


    后台返回的数据:

    [
      {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
    }
  • 相关阅读:
    摄影初识之一
    Photoshop CS6的安装
    chcon可实现对文件的SEAndroid安全标签的修改
    ubuntu启动失败the system is running in low graphics mode
    将ubuntu14.04设置为文本模式启动?
    Android数据库之SQLite数据库
    系统崩溃分析
    Oops 的栈信息分析
    android framework 之JNI
    SecureCRT语法高亮设置
  • 原文地址:https://www.cnblogs.com/cnundefined/p/6962286.html
Copyright © 2020-2023  润新知