查詢表單,一次輸入多個參數(shù),一般是從網(wǎng)站或者excel中復制,要求前端用空格、逗號或者回車切割參數(shù),傳給后端。
這個需求也很常見,之前是先用 split 分隔成數(shù)組,再用 map 遍歷去掉首尾空格,最后再用 filter 來過濾下空值,但是這樣需要遍歷兩次,如果想只用一個 map 實現(xiàn),那還得額外定義個變量來儲存數(shù)據(jù)。
其實像這種組裝數(shù)據(jù)直接用 reduce 就能完美解決,一般有的后端要求用戶沒填的參數(shù)就不傳,不需要傳個空字符串或者空數(shù)組這種,那我們reduce的初始值直接給成 undefined 就不會傳給后端了,不過注意 push 的時候就要額外判斷下了,否則會報錯。
用回車、中英文逗號或空格分隔字符正則:/\n+|,|,|\s+/g
利用 reduce 過濾組裝數(shù)據(jù) demo:
let a = [' ', '1 ', 'zhou', ' ']
let b = a.reduce((m, n) => {
if (n) {
const txt = n.trim()
if (txt) m.push(txt)
}
return m
}, [])
console.log(b) // ['1', 'zhou']
項目中使用完整示例代碼:
// 請求數(shù)據(jù)
async query() {
const { orderIds, names } = this.queryForm
let params = {
page: this.page.index,
size: this.page.size,
}
this.fmtParams(params, 'orderIds', orderIds)
this.fmtParams(params, 'names', names)
const res = await this.$axios({
method: 'post',
url: 'cafe123/api/info',
data: params,
})
if (res.success) {
console.log(res)
}
}
// 格式化參數(shù)
fmtParams(params, key, val) {
// if (val) {
// params[key] = val.split(/\n+/g).map(a => a.trim()).filter(a => a)
// }
if (val) {
// 初始值設(shè)為 undefined,未填寫有效數(shù)據(jù)時不需要傳參數(shù),如都是敲的空格、回車
// 以回車、中英文逗號或空格分隔
const list = val.split(/\n+|,|,|\s+/g)
params[key] = list.reduce((m, n) => {
if (n) {
const txt = n.trim()
if (txt) {
if (!m) m = []
m.push(txt)
}
}
return m
}, undefined)
}
}