在Angular 7中并排合并两个数组

时间:2019-01-11 07:16:09

标签: javascript angular typescript angular7

要并排合并两个数组,我遵循以下过程,但得到

  

无法设置未定义的属性“帐户”。

这是我的代码

    //MARK: - Multiple Images Uploading API Call
        func serviceUploadMultipleImageData(model : UploadImageResponseModel,isLoader:Bool = true,name:String = "", loaderViewcontoller : UIViewController? = nil,url: String, method: HTTPMethod, InputParameter: Parameters?, ServiceCallBack: @escaping (_ Completion: ServiceResponseNormal, _ isSuccess:Bool)-> Void) {
            let viewContoller = loaderViewcontoller
            guard Reachability.isConnectedToNetwork() else {
                Singleton.sharedSingleton.showPopup(title: "No Internet", message: HttpCode.NoInternetConnection.message(), image: nil, VC: viewContoller!)
                ServiceCallBack(self.setCustomResponse(Code: HttpCode.NoInternetConnection.rawValue, Message: "No Internet Connection"),false)
                return
            }
            if isLoader == true {
                if viewContoller != nil {
                    ProgressHUD.startLoading(onView: (viewContoller?.view)!)
                } else {
                    ProgressHUD.startLoading(onView: appDelegate.window!)

                }
            }

            Alamofire.upload(multipartFormData: { (multipartFormData) in

                for obj in model.arrImages{
                multipartFormData.append(obj.imageData!, withName:obj.imgName, fileName: "", mimeType: "image/jpg")
}
                for (key, value) in InputParameter! {
                    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue, allowLossyConversion: true)!, withName: key)
                }
            }, to:url)
            { (result) in
                switch result {
                case .success(let upload, _, _):

                    upload.uploadProgress(closure: { (Progress) in
                        model.progress = Progress.fractionCompleted
                    })

                    upload.responseJSON { response in
                        if isLoader == true {
                            if viewContoller != nil {
                                ProgressHUD.stopLoading(fromView: (viewContoller?.view)!)
                            }else {
                               ProgressHUD.stopLoading(fromView: appDelegate.window!)
                            }
                        }
                        if(response.result.isSuccess){
                            print(response)
                            do{
                                if response.data != nil{
                                    var responseParsed = try JSONDecoder().decode(ServiceResponseNormal.self, from: response.data!)
                                    if responseParsed.Code == "200"
                                    {
                                        responseParsed.Data = response.data
                                        ServiceCallBack(responseParsed, true)
                                    }
                                    else
                                    {
                                        Singleton.sharedSingleton.showPopup(title: "Error", message: responseParsed.Message ?? "Error", image: nil, VC: viewContoller!)
                                        ServiceCallBack(responseParsed, false)
                                    }
                                }
                            }
                            catch let error {
                                print(error.localizedDescription)
                                var falilure = ServiceResponseNormal()
                                falilure.Data = nil
                                falilure.Message = "Response could not parsed"
                                ServiceCallBack(falilure, false)
                            }
                        }
                        else{
                            if let error = response.result.error{
                                let message = error.localizedDescription
                                var falilure = ServiceResponseNormal()
                                falilure.Data = nil
                                falilure.Message = message
                                ServiceCallBack(falilure, false)
                                Singleton.sharedSingleton.showPopup(title: "Error", message: message, image: nil, VC: viewContoller!)
                            }
                        }
                    }
                case .failure(let encodingError):
                    let message = encodingError.localizedDescription
                    var falilure = ServiceResponseNormal()
                    falilure.Data = nil
                    falilure.Message = message
                    ServiceCallBack(falilure, false)
                    Singleton.sharedSingleton.showPopup(title: "Error", message: message, image: nil, VC: viewContoller!)
                }
            }


        }

如果我这样添加 acs = [ { "account": "Cash In Hand", "liabilities": 0, "assets": 8031597 }, { "account": "Tax Acs", "liabilities": 988363.72, "assets": 0.98 }, { "account": "Sundry Debtor", "liabilities": 0, "assets": 551 }, { "account": "Sundry Creditor", "liabilities": 0, "assets": 0 } ]; acd: any; acc: any; newacc: any; constructor() { } ngOnInit() { this.acd = this.acs.filter(f => f.liabilities !== 0); this.acc = this.acs.filter(f => f.assets !== 0); const bigger = this.acd.length > this.acc.length ? this.acd.length : this.acc.length; this.newacc = []; for (let i = 0; i < bigger; i++) { if (this.acd.length > i) { this.newacc[i].account = this.acd[i].account; this.newacc[i].liabilities = this.acd[i].liabilities; } if (this.acc.length > i) { this.newacc[i].accounts = this.acc[i].account; this.newacc[i].assets = this.acc[i].assets; } } } ,第二个this.newacc = [{}];也会收到相同的错误,即if

我在这里犯了什么错误?还是有最简单的方法将两个数组并排组合?这两个数组在数组长度上是独立的,并且不进行任何连接。

2 个答案:

答案 0 :(得分:0)

您应该使用push方法。问题是您要使用C++这样的语法添加元素。

 this.newacc[i].account = this.acd[i].account;

如前所述,可以通过传递所需的 object 作为参数来使用push方法。

newacc.push({account:acd[i].account, liabilities : acd[i].liabilities });

acs = [ { "account": "Cash In Hand", "liabilities": 0, "assets": 8031597 }, { "account": "Tax Acs", "liabilities": 988363.72, "assets": 0.98 }, { "account": "Sundry Debtor", "liabilities": 0, "assets": 551 }, { "account": "Sundry Creditor", "liabilities": 0, "assets": 0 } ];

acd = acs.filter(f => f.liabilities !== 0);
acc = acs.filter(f => f.assets !== 0);

const bigger = acd.length > acc.length ? acd.length : acc.length, newacc = [];
for (let i = 0; i < bigger; i++) {
  if (acd.length > i)
    newacc.push({account:acd[i].account, liabilities : acd[i].liabilities });
  if (acc.length > i)
    newacc.push({account:acc[i].account, assets : acc[i].assets });
}
console.log(newacc);

答案 1 :(得分:0)

您的问题纯粹是一个Typescript问题,其中没有棱角。

这是部分代码的修复程序,其余的我想您可以弄清楚:

interface accnt {
  account: string;
  liabilities: number;
  assets: number;
}

let acs = [
    {
        "account": "Cash In Hand",
        "liabilities": 0,
        "assets": 8031597
    },
    {
        "account": "Tax Acs",
        "liabilities": 988363.72,
        "assets": 0.98
    },
    {
        "account": "Sundry Debtor",
        "liabilities": 0,
        "assets": 551
    },
    {
        "account": "Sundry Creditor",
        "liabilities": 0,
        "assets": 0
    }
];

let acd: accnt[] = new Array(4);
let acc: accnt[] = new Array(4);
let newacc: accnt[] = new Array(4);

this.acd = this.acs.filter(f => f.liabilities !== 0);
this.acc = this.acs.filter(f => f.assets !== 0);
alert(JSON.stringify(this.acd));
alert(JSON.stringify(this.acc));
alert(JSON.stringify(this.newacc));

const bigger = this.acd.length > this.acc.length ? this.acd.length : this.acc.length;

for (let i = 0; i < bigger; i++) {
  if (this.acd.length > i) {
    this.newacc[i] =
      {
        account: this.acd[i].account,
        liabilities: this.acd[i].liabilities
      }
  }
  /*if (this.acc.length > i) {
    this.newacc[i].accounts = this.acc[i].account;
    this.newacc[i].assets = this.acc[i].assets;
  }*/
}

alert(JSON.stringify(this.newacc));