Skip to content

Instantly share code, notes, and snippets.

@stramel
Created June 13, 2019 06:43
Show Gist options
  • Save stramel/3514f9f7611ebaf87ce55b7e6357c0fb to your computer and use it in GitHub Desktop.
Save stramel/3514f9f7611ebaf87ce55b7e6357c0fb to your computer and use it in GitHub Desktop.
Playing around with creating an object from a path string for react-hook-form
const values = {
'property': 'foo',
'categories[1]': 'action',
'categories[0]': 'adventure',
'debug.works': 'true',
'person[0].active': 'true',
'person[0].name.first': 'testFirst',
'person[0].name.last': 'testLast',
'person[0].numbers[0]': '1234',
'person[0].numbers[1]': '5678',
'person[2].firstName': 'John',
'person[2].lastName': 'Doe',
'person[1].name.first': 'John',
'person[1].name.last': 'Doe',
}
function build(acc, path, value) {
if (path === '') {
return value
}
const index = path.search(/[\[\.]/)
const hasMore = index !== -1
let key = path.slice(0, hasMore ? index : undefined)
const result = key.match(/^(\d+)\]$/);
if (result) {
acc = acc || []
key = result[1]
} else {
acc = acc || {}
}
acc[key] = build(acc[key], hasMore ? path.slice(index + 1) : '', value)
return acc
}
function combine(vals) {
return Object.entries(vals).reduce((obj, [path, value]) => {
return build(obj, path, value)
}, {})
}
console.log(combine(values))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment