节点js中的数组对象重叠

时间:2018-08-01 04:23:07

标签: javascript node.js express hyperledger-fabric blockchain

我在请求正文中得到一个数组,如:

[
   {
     "month": "JUL",
     "year": "2018"
   },
   {
     "month": "JAN",
     "year": "2018"
   },
   {
     "month": "MAR",
     "year": "2018"
   }
 ]

此输入有两个参数(month:enumyear:string)。

我需要遍历此数组并调用链码,最后发送响应。我已完成以下操作:

for (var i = 0; i < req.body.length; i++) {
  var month = req.body[i].month;
  var year = req.body[i].year;
  var monthYear = month + year;
  key = monthYear + "_new";
  console.log("Key is ", key);
  var request = {
    //targets: let default to the peer assigned to the client
    chaincodeId: 'abc',
    fcn: 'getTransactionsByKey',
    args: [key]

    //Calling chaincode smartcontract
    return channel.queryByChaincode(request);
  }

,但如果我仅传递一个输入参数,则响应正确。如果我在输入中传递两个值,则第二个值结果将覆盖第一个值。关于如何获得重叠部分的所有输入列表的响应的任何帮助。

此外,我需要在调用链码之前对输入值进行排序,例如,如果输入中输入Feb Mar Jan,则应将其排序为Jan Feb Mar,然后运行for循环。

对此有任何帮助。

谢谢。

2 个答案:

答案 0 :(得分:0)

尝试此代码可能对您有用

var request=[];
 for(var i=0; i<req.body.length; i++) {
                    var month =req.body[i].month;
                    var year = req.body[i].year;
                    var monthYear = month + year;
    key = monthYear + "_new";
        console.log("Key is ", key);
             request.push( {
            //targets: let default to the peer assigned to the client
             chaincodeId: 'abc',
             fcn: 'getTransactionsByKey',
             args: key
             });

//Calling chaincode smartcontract
}
  console.log(request);
 return channel.queryByChaincode(request);

输出:

[ { chaincodeId: 'abc',
    fcn: 'getTransactionsByKey',
    args: 'JAN2018_new' },
  { chaincodeId: 'abc',
    fcn: 'getTransactionsByKey',
    args: 'JUL2018_new' },
  { chaincodeId: 'abc',
    fcn: 'getTransactionsByKey',
    args: 'MAR2018_new' } ]

答案 1 :(得分:0)

创建所有请求对象的数组,并将其传递给queryByChaincode。

var requests = req.body.map((body) => {
    return {
        chaincodeId: 'abc',
        fcn: 'getTransactionsByKey',
        args: [`${body.month}${body.year}_new`]
    };
});
return channel.queryByChaincode(requests);