首页 > 解决方案 > 如何从数组中想要形成一个模式来进行查询以进行 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);
        });

标签: javascriptnode.jsarraysapiaxios

解决方案


使用mapandjoin构建参数字符串

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);


推荐阅读