将具有数组值的对象键转换为查询字符串

问题描述 投票:1回答:1

我正在尝试将对象转换为查询字符串,但是我有一个数组作为值

我的对象看起来像这样

filterChoice: { role: ["SW", "EW"] source: ["Secondary", "Tertiary"] }

我已经完成转换了一半

const toQueryString = `?${Object.keys(filterChoice)
    .map(key => `${key}=${filterChoice[key].toString()}`)
    .join('&')}`

输出:?source=Secondary,Tertiary&role=SW,EW但我希望此输出看起来像这样

?source=Secondary&source=Tertiary&role=SW&role=EW

有人可以帮我吗?

javascript oop ecmascript-6
1个回答
0
投票

您可以flatMap对象条目:

 const query = Object.entries(filterChoice)
  .flatMap(([key, value]) => Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]])
  .map(it => it.join("="))
  .join("&");
© www.soinside.com 2019 - 2024. All rights reserved.