Skip to content

omitStartWithKeys

移除对象/数组中以指定字符开头的属性(支持对象、对象数组、普通数组、多维数组、嵌套结构)

引入版本

0.25.0

Demo

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

/**
 * ================== 基础对象(默认移除 _ 开头 ==================
 */
const obj1 = { id: 1, name: '王独秀', _secret: '机密', $custom: '自定义' }
console.log(omitStartWithKeys(obj1))
// {id: 1, name: '王独秀', $custom: '自定义'}

/**
 * ================== 嵌套对象 ==================
 */
const obj2 = {
  user: { name: '王独秀', _pwd: '123' },
  _token: 'abc123'
}
console.log(JSON.stringify(omitStartWithKeys(obj2), null, 2))
// { user: { name: '王独秀' } }

/**
 * ================== 一维数组(指定移除 $ 开头) ==================
 */
const arr1 = ['1', '2', '$3', '$4', '5']
console.log(omitStartWithKeys(arr1, '$'))
// ['1', '2', '5']

/**
 * ================== 多维数组 ==================
 */
const arr2 = ['1', '2', ['_3', '_4', ['5', '6', ['_7', '8']]]]
console.log(omitStartWithKeys(arr2))
// ['1', '2', [['5', '6', ['8']]]]

/**
 * ================== 对象数组 ==================
 */
const arr3 = [
  { id: 1, name: 'A', _private: 'xxx' },
  { id: 2, name: 'B', _private: 'yyy' }
]
console.log(JSON.stringify(omitStartWithKeys(arr3), null, 2))
// [
//   { id: 1, name: 'A' },
//   { id: 2, name: 'B' }
// ]

/**
 * ================== 嵌套对象 + 多维数组 ==================
 */
const complexData = {
  a: 1,
  _b: 2,
  list: [
    { id: 1, _hide: true },
    [
      { id: 2, _hide: false },
      { id: 3, name: 'test' }
    ]
  ]
}
console.log(JSON.stringify(omitStartWithKeys(complexData), null, 2))
// {
//   "a": 1,
//   "list": [
//     {
//       "id": 1
//     },
//     [
//       {
//         "id": 2
//       },
//       {
//         "id": 3,
//         "name": "test"
//       }
//     ]
//   ]
// }

基于 MIT 许可发布