Reputation: 153
I have data record
record: {
address: {
city: ""
}
}
array of objects that describe field
fields: [
{
name: "address.city"
...
}
]
and try to generate form
<b-field
v-for="field in fields"
:key="field.name"
:label="field.label"
>
<b-input v-model="record[field.name]" />
</b-field>
and get object item with key like address.name
I understand that i should pass to v-model record[address][city]
but how to do it from dot delimited string?
Is it possible?
Upvotes: 3
Views: 1147
Reputation: 943
const getPathInObject = (path, object) => {
const [current, ...rest] = path.split('.')
return rest.length === 0
? object[current]
: getPathInObject(rest.join('.'), object[current])
}
document.write(getPathInObject('a.b.c.d', { a: { b: { c: { d: 'hello' } } } }))
const unflatten = obj => {
const result = {};
Object.entries(obj).forEach(([key, value]) => {
const [a, b] = key.split('.');
result[a] ||= {};
result[a][b] = value
})
return result
}
new Vue({
el: "#app",
data: {
record_flat: {"address.city": '', "address.country": ''},
fields: [
{ name: "address.city", label: 'city' },
{ name: "address.country", label: 'country' }
]
},
computed: {
record: ({ record_flat }) => unflatten(record_flat),
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="{name, label} in fields" :key="name">
<label>{{ label }}</label><input v-model="record_flat[name]" />
<br>
</div>
<hr>Value of record = {{ record }}
</div>
Upvotes: 2
Reputation: 153
I used :value
and @input
instead v-model
.
And lodash get
and set
<b-input
:value="get(data, field.name)"
@input="set(data, field.name, $event)"
/>
Upvotes: 1