Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions src/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,11 +323,26 @@ export const keys = <TValue extends object>(value: TValue): string[] => {
*/
export const crush = <TValue extends object>(value: TValue): object => {
if (!value) return {}
return objectify(
keys(value),
k => k,
k => get(value, k)
)
const crushImpl = (
nested: any,
paths: string[],
result: Record<string, any>
): void => {
if (isObject(nested)) {
for (const [k, v] of Object.entries(nested)) {
crushImpl(v, [...paths, k], result)
}
} else if (isArray(nested)) {
for (let i = 0; i < nested.length; i++) {
crushImpl(nested[i], [...paths, `${i}`], result)
}
} else {
result[paths.join('.')] = nested
}
}
const result: Record<string, any> = {}
crushImpl(value, [], result)
return result
}

/**
Expand Down
12 changes: 12 additions & 0 deletions src/tests/object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,18 @@ describe('object module', () => {
timestamp: now
})
})
test('preserves values when object keys contain dots', () => {
const obj = {
key1: {
key2: 'value'
},
'bar.baz': 'fiz'
}
assert.deepEqual(_.crush(obj), {
'key1.key2': 'value',
'bar.baz': 'fiz'
})
})
})

describe('construct function', () => {
Expand Down