Skip to content

Commit

Permalink
fixes support dot in property name #23
Browse files Browse the repository at this point in the history
  • Loading branch information
stefaanv committed Jul 8, 2024
1 parent e789c1f commit ff42743
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 9 deletions.
37 changes: 29 additions & 8 deletions src/object/crush.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { objectify } from 'radashi'
import { get } from 'radashi'
import { keys } from 'radashi'
import { isDate, isPrimitive, objectify } from 'radashi'

/**
* Flattens a deep object to a single demension, converting the keys
Expand All @@ -10,11 +8,34 @@ import { keys } from 'radashi'
* crush({ name: 'ra', children: [{ name: 'hathor' }] })
* // { name: 'ra', 'children.0.name': 'hathor' }
*/
export const crush = <TValue extends object>(value: TValue): object => {
type Primitive =
| number
| string
| boolean
| Date
| symbol
| bigint
| undefined
| null

export const crush = <TValue extends object>(
value: TValue
): Record<string, Primitive> | Record<string, never> => {
if (!value) return {}
return objectify(
keys(value),
k => k,
k => get(value, k)
const crushToPvArray: (
obj: object,
path: string
) => Array<{ p: string; v: Primitive }> = (obj: object, path: string) =>
Object.entries(obj).flatMap(([key, value]) =>
isPrimitive(value) || isDate(value)
? { p: path === '' ? key : `${path}.${key}`, v: value }
: crushToPvArray(value, path === '' ? key : `${path}.${key}`)
)

const result = objectify(
crushToPvArray(value, ''),
o => o.p,
o => o.v
)
return result
}
26 changes: 25 additions & 1 deletion src/object/tests/crush.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,36 @@ describe('crush function', () => {
timestamp: now
})
})
test('handles property names with dots', () => {
test('handles property names with dots 1', () => {
const obj = {
a: { 'b.c': 'value' }
}
expect(_.crush(obj)).toEqual({
'a.b.c': 'value'
})
})
test('handles property names with dots 2', () => {
const obj = {
'a.b': { c: 'value' }
}
expect(_.crush(obj)).toEqual({
'a.b.c': 'value'
})
})
test('handles property names with dots 3', () => {
const obj = {
'a.b': { 'c.d': 123.4 }
}
expect(_.crush(obj)).toEqual({
'a.b.c.d': 123.4
})
})
test('handles arrays', () => {
const obj = ['value', 123.4, true]
expect(_.crush(obj)).toEqual({
'0': 'value',
'1': 123.4,
'2': true
})
})
})

0 comments on commit ff42743

Please sign in to comment.