javascript - 如何从数组中想要形成一个模式来进行查询以进行 API 调用
问题描述
我想从数组中派生出一个模式。数组可以是n
元素的数量
这是我从 DB 收到的数组模式,(注意这里的元素可能是n
数字)
[
{ id: '2', name: 'ONe' },
{ id: '3', name: 'Twop' },
{ id: '1', name: 'ThreeC' }
]
我想要一个像AccountId=2&AccountId=3&AccountId=1
从数组和id
其中形成的模式
我想将形成的数据作为查询参数传递到下面的 URL 中以进行 API 调用。
const config = {
method: 'get',
url: `${URL}api/cost?AccountId=1&AccountId=2&AccountId=3`,
headers: {
'Cookie': 'ARRAffinity=6f6eb54d3b6d7ed13173b9203b0bd6571b611d626818fba77a815805a7c90146'
},
data: data
};
const dataOutput = await axios(config )
.then(function (response) {
console.log(JSON.stringify(response.data));
return response.data;
})
.catch(function (error) {
console.log(error);
});
解决方案
使用map
andjoin
构建参数字符串
const data = [
{ id: "2", name: "ONe" },
{ id: "3", name: "Twop" },
{ id: "1", name: "ThreeC" },
];
const params = data.map(({ id }) => `AccountId=${id}`).join("&");
const url = `foo.com/api/cost?${params}`;
console.log(url);
推荐阅读
- c++ - 在定义外联时向已经模板化的类的方法添加额外的模板参数
- javascript - gtag 集未按预期附加数据
- c++ - 如何在应用程序字体大小更改后相应调整的小部件上设置自定义字体大小?
- python - 循环一列并删除字符 - Python Pandas
- passwords - how to find Bitnami hadoop appliance password?
- scala - call-by-name function is evaluated before invoke
- powershell - 在powershell中制作别名的最简单方法是什么?
- javascript - Keeping iframe/image ratio when resizing on height
- python - 要从 sftp 服务器下载文件夹,它会在本地目录中下载文件夹,但是当我给出特定的文件路径时,它会显示错误
- javascript - 按最大值对 Javascript 对象数组进行排序