循环并连接相同的VAR

时间:2017-05-19 10:28:46

标签: javascript arrays loops

是否可以使用do{}while()根据另一个var的结果连接相同的var?

我正在运行一个循环,我捕获客户及其付款,每一行都是结果,有时对同一个客户我有2个或更多付款,即:

Customer A --- 'Payment#01' --- $10.00 Customer A --- 'Payment#02' --- $10.00 Customer B --- 'Payment#01' --- $10.00 Customer B --- 'Payment#02' --- $10.00 Customer B --- 'Payment#03' --- $10.00 [...]

我想在第一行检查客户,while下一行继续使用同一个客户我想将每个结果连接成一个字符串,所以我会这样:

Customer A --- 'Payment#01,Payment#02' --- $20.00 Customer B --- 'Payment#01,Payment#02,Payment#03' --- $30.00

[编辑:目前为止的代码]

try{
    do{
        resultSet = searchResults.getResults(resultIndex, resultIndex + resultStep); 
        resultIndex = resultIndex + resultStep; 
        for(var i = 0; !!resultSet && i < resultSet.length; i++){
            var results = resultSet[i];
            var columns = results.getAllColumns();
            var customer = results.getValue(columns[0]);
            var paymentamt = results.getValue(columns[1]);
            var document = results.getValue(columns[2]);
        } 
    } while (!!resultSet && resultSet.length > 0)
} catch(error){
    var message = error.message;
}

2 个答案:

答案 0 :(得分:0)

如果客户总是处于整洁的订单中,即您无法获得客户A,客户B,客户A,那么只需使用变量来跟踪当前客户ID,当前支付字符串和当前价值。

循环通过该批次 - [循环]中的客户ID与当前的客户ID相同吗?如果是,请添加到字符串和值。 如果没有,输出(或用它做的任何事情)当前行,将所有变量重置为这个新客户的数据。

如果他们可以 out 订购,那么您可以将值存储在对象中 - 例如。 customerRecord = {customerID:{paymentstring:,value:}}。 当您在循环中读取下一个客户时,检查它是否存在于对象中(如果您将customerID用作上述键,则为hasOwnProperty)并添加其值。如果没有,请将新对象添加到customerRecord。

答案 1 :(得分:0)

最通用的方法是使用密钥或更现代的Map来保留对象以保留总计和所有付款。最直接的方法是保留对象并简单地保持附加字符串。另一种方法是将单独的付款(描述)保留在这些对象中,并仅在显示时将它们连接起来。例如:

//this part is just for emulating the resultset
let resultSet =[	{vals:['Customer A' ,'Payment#01' ,10.00]},  {vals:['Customer A' ,'Payment#02' ,10.00]},  {vals:['Customer B' ,'Payment#01' ,10.00]},  {vals:['Customer B' ,'Payment#02' ,10.00]},  {vals:['Customer B' ,'Payment#03' ,10.00]}  ];resultSet.forEach(o=> {o.getAllColumns = ()=> [0,1,2]; o.getValue = i => o.vals[i]});
  

let map = new Map(); // <- declare outside the do..while , if it should concatenate customers from all searches, otherwise inside
do{
	//get result set code...
	if(!resultSet)break;
  	for(var i = 0; i < resultSet.length; i++){    
            let results = resultSet[i],
            	columns = results.getAllColumns();
             	customer = results.getValue(columns[0]),
            	tot = map.get(customer);
            if(!tot) map.set(customer,tot = {customer:customer, payments:[], totalAmt:0, get Payments(){return this.payments.join(', ');} , toString: function(){return `${this.customer} --- ${this.Payments} --- ${this.totalAmt}`;}});
            tot.payments.push(results.getValue(columns[1]));
            tot.totalAmt += results.getValue(columns[2]);
        }     
}while(false); //replace with your own while (since break is used, you could simply do while(true))

//test output code. 
for(let tot of map.values())
	console.log(tot.toString());