Skip to content

expandCommaKeyObject

展开对象中逗号分隔的键值对

引入版本

0.15.0

Demo

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

/**
 * ================== 1. 顶层逗号键 ==================
 */
const case1 = {
  'name,age': ['张三', 18],
  sex: '男'
}
console.log(expandCommaKeyObject(case1))
// { name: '张三', age: 18, sex: '男' }

/**
 * ================== 2. 嵌套对象内部逗号键 ==================
 */
const case2 = {
  user: {
    'username,avatar': ['admin', 'https://xxx.png']
  }
}
console.log(JSON.stringify(expandCommaKeyObject(case2), null, 2))
/*
{
  user: { username: 'admin', avatar: 'https://xxx.png' }
}
*/

/**
 * ================== 3. 多层深度嵌套 ==================
 */
const case3 = {
  a: {
    b: {
      'x,y,z': [10, 20, 30]
    }
  }
}
console.log(JSON.stringify(expandCommaKeyObject(case3), null, 2))
/*
{
  a: { b: { x: 10, y: 20, z: 30 } }
}
*/

/**
 * ================== 4. 多层混合多个逗号键 ==================
 */
const case4 = {
  'id,phone': [1, '13800138000'],
  info: {
    'province,city': ['四川', '宜宾'],
    extra: {
      'label,value': ['启用', 1]
    }
  }
}
console.log(JSON.stringify(expandCommaKeyObject(case4), null, 2))
/*
{
  id: 1,
  phone: '13800138000',
  info: {
    province: '四川',
    city: '宜宾',
    extra: { label: '启用', value: 1 }
  }
}
*/

/**
 * ================== 5. 逗号键对应非数组,不处理 ==================
 */
const case5 = {
  'title,desc': '文本',
  inner: { 'a,b': null }
}
console.log(JSON.stringify(expandCommaKeyObject(case5), null, 2))
// 原样保留原逗号key

/**
 * ================== 6. 数组长度与key数量不匹配 ==================
 */
const case6 = {
  'm,n': [1],
  sub: { 'x,y': [1, 2, 3] }
}
console.log(JSON.stringify(expandCommaKeyObject(case6), null, 2))
// { m: 1, n: undefined, sub: { x: 1, y: 2 } }

/**
 * ================== 7. 空对象 ==================
 */
console.log(expandCommaKeyObject({})) // {}

/**
 * ================== 8. 无逗号键,原样返回 ==================
 */
const case8 = { a: 1, b: { c: 2 } }
console.log(JSON.stringify(expandCommaKeyObject(case8), null, 2))

/**
 * ================== 9. 非法入参 ==================
 */
console.log(expandCommaKeyObject(null))
console.log(expandCommaKeyObject(undefined))
console.log(expandCommaKeyObject(123))
console.log(expandCommaKeyObject([]))
console.log(expandCommaKeyObject('abc'))
// 全部返回 {}

基于 MIT 许可发布