动态填充字符串字面模板



每当我从列表中选择一个人时,它就会获取一个名字的id,并将其存储为一个带有map的数组。

然后我有一个字符串文字,里面填充了ID。

const id = value.map(person => person.value)
console.log('from',id)

电流输出:

[u29219]

结果如下:

const results = await verifiedGet(`get_user/?$u29219?admin_form=True`, user.user)

然后如果我再加一个人,阵列就会像这个

[u29219, u302932]

结果:

const results = await verifiedGet(`get_user/hello?$u29219,u302932?admin_form=True`, user.user)

当一个用户被添加到数组中时,如果一个用户选择了两次,我希望能够在ID只填充一次的情况下迭代结果

const results = await verifiedGet(`get_user/?$u29219?admin_form=True`, user.user)
const results = await verifiedGet(`get_user/?$u302932?admin_form=True`, user.user)

这样做可能吗?

我创建了一个沙盒来更好地理解

https://codesandbox.io/s/modest-star-fegy7

我会使用您唯一的id数组,并使用array.Join((将它们与逗号组合。

// Map the ids, and filter unique
const uniqueIds = value
.map((person) => person.value)
.filter((value, index, self) => self.indexOf(value) === index);
// Join the Ids and separate them with commas
const commaSeparatedIds = uniqueIds.join[','];
// Don't forget to make them safe for a URL
// You may be able to skip this if you are certain 
// your string is safe
const uriSafeIds = encodeURIComponent(commaSeparatedIds);
// Finally, interpolate into your string literal template
// I wasn't sure if the extra $ in your code was intended
// so I left it in.
const url = `get_user/hello?$${uriSafeIds}?admin_form=True`;
const results = await verifiedGet(url, user.user);

const id = user.map((person) => person);行中,我们循环遍历'user'数组,对于每次迭代,我们只是返回该迭代中的元素。"map"函数将返回每次迭代中返回的数组。因此,基本上,我们在id中重新创建user数组。

const user = ["u29219", "u302932"];
// 'user' array is re-created here
const id = user.map((person) => person);
console.log("from", id);
const results = `get_user/?${id}admin_form=True`;

如果您的意图是用数组中的每个元素形成results字符串,那么这将是一种使用forEach:的方法

user.forEach((person) => {
const results = `get_user/?${person}$admin_form=True`;
// remaining logic
});

代码沙盒

可以使数组唯一,然后进行concat或join以获得预期的输出。

const user = ["u29219", "u302932", "u302932"];
const uniqueItems = [...new Set(user)];
console.log("current uniqueItems", uniqueItems);
let results = "";
uniqueItems.forEach((person) => {
results = results.concat(`get_user/?${person}$admin_form=True `);
});
console.log("current output", results);

相关内容

  • 没有找到相关文章

最新更新