首页 > 解决方案 > 如何在打字稿中将对象数组转换为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);

控制台日志始终为空。这可以以更好的方式完成吗?

请注意,我需要小写的所有字段值而不是驼峰式。请协助。

标签: typescript

解决方案


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


推荐阅读