[英]Loop through an array list to make a post request for a rest API dynamic
I update an object.我更新了 object。 This object is an array which can have a length from one to five.
这个 object 是一个长度可以从 1 到 5 的数组。 This is my object
["max", "dog"]
.这是我的 object
["max", "dog"]
。
Now a post method is to be called.现在要调用一个 post 方法。 It is so if the user has only 2 things filled in, only two things should be sent there.
因此,如果用户只填写了 2 个东西,那么应该只将两个东西发送到那里。 If 5 then 5 (see example for a better explanation.) Does anyone have an idea how best to set this up?
如果 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);
});
};
What I try我尝试什么
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);
});
};
My loop doesn't really make much sense.我的循环并没有多大意义。 How can I add this to an object so that it can be sent in later in an API?
如何将其添加到 object 以便稍后在 API 中发送?
You can use Object.fromEntries()
to map an array of arrays to object, like in the following example:您可以使用
Object.fromEntries()
到 map 的数组 arrays 到 ZA8CFDE63311449EB2AC96F8 示例如下:
const arr = ["max", "dog"]; const mapped = arr.map((el, i) => [`first${i+1}`, el]); console.log(Object.fromEntries(mapped))
You can also use Array.prototype.reduce()
to achieve the same thing:您还可以使用
Array.prototype.reduce()
来实现相同的目的:
const arr = ['cat', 'dog']; const obj = arr.reduce((acc, cur, i) => ((acc[`first${i + 1}`] = cur), acc), {}); console.log(obj);
Reference: Convert Array to Object参考:将数组转换为 Object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.