javascript - 使用 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]);
}
解决方案
根据OP,sendData(data);
是正确的解决方案。
推荐阅读
- flutter - 使用图像包将图像拆分/划分为 6 块
- c - 一般来说,如何防止C语言中发生整数溢出?
- hybris - SAP 物料集成中冗余产品数据的处理
- azure - Azure 数据工厂,将 REST GET 响应传递给 Azure SQL 数据库中的存储过程
- c++ - 完成构建项目“Error.vcxproj”——失败
- python - 在mnist中重新缩放图像
- python - Plotly:躲避散点图分类轴上的重叠点
- python - Instapy“无效的类似元素!”
- ios - Firebase 能源影响
- ios - NotificationServiceExtension 是否适用于本地通知?