Skip to content

Instantly share code, notes, and snippets.

@calebporzio
Created November 2, 2018 16:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save calebporzio/371d8421ac5ea660ad7ce174c345122b to your computer and use it in GitHub Desktop.
Save calebporzio/371d8421ac5ea660ad7ce174c345122b to your computer and use it in GitHub Desktop.
A Vue component for turning json into hidden input elements
// Usage:
// <input-hidden name="users" :value="[{name: 'Caleb'}, {name: 'Daniel'}]"/>
// (value can be a: string, integer, array, object)
//
// will render:
// <input class="hidden" type="text" name="users[0][name]" value="Caleb">
// <input class="hidden" type="text" name="users[1][name]" value="Daniel">
<script>
import _ from 'lodash'
export default {
functional: true,
props: [ 'name', 'value' ],
render(h, context) {
function wrapInBrackets(keys) {
return keys.length
? '[' + Array.from(keys).join('][') + ']'
: ''
}
function flatInputsFromDeepJson(item, key, h) {
if (typeof item === 'object') {
return _.flatMapDeep(item, (value, newKey) => {
return flatInputsFromDeepJson(value, key.concat(newKey), h)
})
}
return h('input', { attrs: {
class: 'hidden',
type: 'text',
name: context.props.name + wrapInBrackets(key),
value: item,
}})
}
return flatInputsFromDeepJson(context.props.value, [], h)
},
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment