首页 > 解决方案 > 使用 for 循环切换后的数组值

问题描述

我有一个脚本,它遍历一个数组并对我的 API 进行 POST 调用以创建新记录。当它运行时,我看到为数组中的每个值创建了新记录,但我无法通过 tens/u_department 值(数组值)我必须进行切换,因为输入值在该格式下无效在我的 API 中。

如何从以下请求中获得以下响应。

要求

    {"caller_id":"caller","description":"description","u_department":"A B.C"}
    {"caller_id":"caller","description":"description","u_department":"D E.F"}
    {"caller_id":"caller","description":"description","u_department":"H I.J"}

期望的响应

{"result":{"caller_id":"caller","description":"description","u_department":"A B.C"},"record":"1"}}
{"result":{"caller_id":"caller","description":"description","u_department":"D E.F"},"record":"2"}}
{"result":{"caller_id":"caller","description":"description","u_department":"G H.I"},"record":"3"}}

脚本

//Input tenants "ABC, DEF, GHI....."
var tens = "ABC, DEF, GHI"
console.log(tens);

var realten = input.tenants;
var realten = realten.split(',');
console.log(realten);

var letters = tens.split(',').map(string=>string.trim());
console.log(letters);


//Send data
var data = {};

var caller_id = "caller";
data.caller_id = caller_id;

var description = "description";
data.description = description;

//Convert tens to proper format
var site = {};

switch (realten[0]) {

    case 'ABC':
        site = "A B.C";
        break;

    case 'DEF':
        site = "D E.F";
        break;

    case 'GHI':
        site = "G H.I";
        break;

    case 'JKL':
        site = "J K.L";
        break;

    case 'MNO':
        site = "M N.O";
        break;
}

var u_department = site;
data.u_department = u_department;
console.log(data)

//POST options
  var options = {
    'endpoint': 'test',
    'path':'/api/table/records', 
    'method': 'POST',
    "headers": {
    "Authorization": "Basic xxxxxxxxxxxxxxxxxxx",
    "Content-Type": "application/json"
        } };
        
//I create following function:
function sendData(data) {
    var req = http.request(options, function(res) {
            console.log('STATUS: ' + res.statusCode);
            console.log('HEADERS: ' + JSON.stringify(res.headers));

        });
        req.write(JSON.stringify(data));
}

//end try send for each array item:
for (var i=0; i<letters.length;i++) {
   sendData(data[i]);
}

标签: javascriptnode.jsarraysloopsecmascript-6

解决方案


根据OP,sendData(data);是正确的解决方案。


推荐阅读