Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 循环遍历数组列表以发出RESTAPI动态的post请求_Javascript_Rest_Axios - Fatal编程技术网

Javascript 循环遍历数组列表以发出RESTAPI动态的post请求

Javascript 循环遍历数组列表以发出RESTAPI动态的post请求,javascript,rest,axios,Javascript,Rest,Axios,我更新一个对象。此对象是一个数组,其长度可以为1到5。这是我的对象[“max”,“dog”] 现在将调用post方法。如果用户只填写了两件东西,那么应该只发送两件东西。如果是5,那么是5(参见示例以获得更好的解释)。有人知道如何最好地设置它吗 const tag = ["max", "dog"] const updateInterest = () => { axios .post("...", {

我更新一个对象。此对象是一个数组,其长度可以为1到5。这是我的对象
[“max”,“dog”]

现在将调用post方法。如果用户只填写了两件东西,那么应该只发送两件东西。如果是5,那么是5(参见示例以获得更好的解释)。有人知道如何最好地设置它吗

const tag = ["max", "dog"]
const updateInterest = () => {
    axios
      .post("...", {
        first1: max,
        first2: dog,
        // first3: ...,
        // first4: ...,
        // first4: ...,
      })
      .then((res) => {
        if (res.status === 200) {
          // API update interest
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };
我所尝试的

const tag = ["max", "dog"]
const updateInterest = () => {
    const object = "";
    tags.map((tag, index) =>{
      console.log(tag + " " + index)
      object = 
        `first${index}`: `${tag}`,
      
  })
    axios
      .post("...", {
        object
      })
      .then((res) => {
        if (res.status === 200) {
          // API update interest
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

我的循环没有多大意义。如何将其添加到对象中,以便稍后在API中发送?

您可以使用
object.fromEntries()
将数组数组映射到对象,如以下示例所示:

const arr=[“max”,“dog”];
const-mapped=arr.map((el,i)=>[`first${i+1}`,el]);
console.log(Object.fromEntries(mapped))
您也可以使用它来实现相同的功能:

const arr=['cat','dog'];
const obj=arr.reduce((acc,cur,i)=>(acc[`first${i+1}`]=cur,acc),{});
控制台日志(obj)