Skip to content

stringifyArrayFields

将对象中值为数组的字段转换为逗号分隔的字符串

引入版本

0.15.0

Demo

ts
import { stringifyArrayFields } from '@wyfex/iutils'

/**
 * ================== 1. 标准数组转逗号字符串 ==================
 */
const case1 = { ids: [1, 2, 3], name: 'test' }
console.log(stringifyArrayFields(case1, ['ids']))
// { ids: '1,2,3', name: 'test' }

/**
 * ================== 2. 多字段同时转换 ==================
 */
const case2 = {
  nums: [10, 20],
  tags: ['vue', 'ts'],
  text: 'hello'
}
console.log(stringifyArrayFields(case2, ['nums', 'tags']))
// { nums: '10,20', tags: 'vue,ts', text: 'hello' }

/**
 * ================== 3. 空数组转为空字符串 ==================
 */
const case3 = { list: [] }
console.log(stringifyArrayFields(case3, ['list']))
// { list: '' }

/**
 * ================== 4. 数组含空字符串、null、数字、布尔 ==================
 */
const case4 = { arr: [0, '', null, false, 'a'] }
console.log(stringifyArrayFields(case4, ['arr']))
// { arr: '0,,null,false,a' }

/**
 * ================== 5. 字段不在 includes 内,数组不转换 ==================
 */
const case5 = { data: [1, 2] }
console.log(stringifyArrayFields(case5, ['other']))
// { data: [1, 2] }

/**
 * ================== 6. 字段存在但值不是数组,原样保留 ==================
 */
const case6 = {
  id: 999,
  str: '1,2,3',
  flag: true,
  empty: null
}
console.log(stringifyArrayFields(case6, ['id', 'str', 'flag', 'empty']))
// 全部字段原值不变

/**
 * ================== 7. 不传 includes(默认空数组,无任何转换) ==================
 */
const case7 = { list: [1, 2, 3] }
console.log(stringifyArrayFields(case7))
// { list: [1, 2, 3] }

/**
 * ================== 8. 空对象 ==================
 */
console.log(stringifyArrayFields({}, ['a']))
// {}

/**
 * ================== 9. 嵌套对象(仅顶层生效,子对象数组不处理) ==================
 */
const case9 = {
  ids: [1, 2],
  info: { tags: ['x', 'y'] }
}
console.log(stringifyArrayFields(case9, ['ids', 'tags']))
// { ids: '1,2', info: { tags: ['x', 'y'] } }

/**
 * ================== 10. includes 包含不存在的字段,无副作用 ==================
 */
const case10 = { code: [9, 8] }
console.log(stringifyArrayFields(case10, ['code', 'notExist']))
// { code: '9,8' }

/**
 * ================== 12. 非法入参场景 ==================
 */
console.log(stringifyArrayFields(null, ['ids']))
console.log(stringifyArrayFields(undefined, ['ids']))
console.log(stringifyArrayFields(123, ['ids']))
console.log(stringifyArrayFields('abc', ['ids']))
console.log(stringifyArrayFields([], ['ids']))
// 全部直接返回入参本身

基于 MIT 许可发布