import { isPlainObject } from "../../is" /** * 展平对象为一层的对象 * 深度的属性名用 . 连接,如 { a: { b: 1 } } => { 'a.b': 1 } * @param ob 要展平的对象 * @param options.ignorePrefix 要忽略的前缀,如 `$`,会让 { inf: { parentId: {$in:[]} } } 变成 { 'inf.parentId': {$in:[]} } */ export function flattenObject(ob: any, options?: { ignorePrefix?: string }) { let result: { [path: string]: number | null } = {} each(ob) return result function each(obj: any, prefix: string = ""): void { for (const key in obj) { let shouldFlatten = isPlainObject(obj[key]) if (options?.ignorePrefix) { if (shouldFlatten) { let hasIgnoreKey = Object.keys(obj[key]).some((k) => k.startsWith(options.ignorePrefix!)) if (hasIgnoreKey) shouldFlatten = false } } if (shouldFlatten) { each(obj[key], `${prefix}${key}.`) } else { result[`${prefix}${key}`] = obj[key] } } } } /** * 把 MongoDB 的对象展平 * 会忽略拥有以 `$` 开头的属性的对象 */ export function flattenMongo(ob: any, options?: { ignorePrefix?: string }) { let rootOb: any = {} let readyOb: any = {} for (const key in ob) { if (key.startsWith("$")) { rootOb[key] = flattenObject(ob[key], { ignorePrefix: "$" }) } else { readyOb[key] = ob[key] } } return Object.assign(flattenObject(readyOb, { ignorePrefix: "$" }), rootOb) }