typescript - 如何在打字稿中将对象数组转换为uri编码的查询字符串
问题描述
我是打字稿的新手。我有一个这样的输入数组,
filter = [
{
field : "eventId",
value : "123"
},
{
field : "baseLocation",
value : "singapore"
}
]
我需要这个对象数组,
..test.com?search=eventid%20eq%20123&search=baselocation%20eq%20singapore
我试过这样,但没有任何反应,
var test = '';
if (filter != undefined && filter.length > 0)
filter.array.forEach(item => {
test += Object.keys(item).map(k => `${k}=${encodeURIComponent(item[k])}`);
});
console.log(test);
控制台日志始终为空。这可以以更好的方式完成吗?
请注意,我需要小写的所有字段值而不是驼峰式。请协助。
解决方案
filter.array.forEach
陈述有问题;因为array
是一个未定义的属性,调用forEach
它会导致崩溃。%20eq%20
除此之外,缺少一些您想要的格式组件,例如子字符串和小写字母。
这是一种使用array.map
;发出预期输出的方法 您可以直接索引到对象中,因为只有两个属性:
const filter = [
{
field : "eventId",
value : "123"
},
{
field : "baseLocation",
value : "singapore"
}
];
const expected = `..test.com?search=eventid%20eq%20123&search=baselocation%20eq%20singapore`;
const actual = `..test.com?${filter.map(o =>
`search=${o.field}%20eq%20${o.value}`
).join`&`.toLowerCase()}`;
console.log(actual === expected, actual);
推荐阅读
- msbuild - 如果未签名的 dll 的版本低于项目依赖项之一的要求,msbuild 拒绝复制它 - 这是设计使然吗?
- python - 将 JSON 数据附加到列表时出现“NoneType 对象不可迭代”错误
- css - 如何使用 CSS 从网格中偏移图像?
- javascript - 如何根据 mp4 webm 等对选项进行排序
- sql - SQL模式匹配和替换多个值
- scala - Scala:基于文件列表处理文件夹中文件的最有效方法
- c# - 如何使用 BenchmarkDotNet 运行基准测试,而无需每次运行都构建
- mysql - postgresql中以下sql语句的等价物是什么?
- python - wkt 和 str 的区别
- shell - 如何在命令行中修复“找不到命令”