[英]Building Json Object from Vue input fields
Im trying to generate a JSON object with a vue method and using vue input data fields to build part of the JSON object.我尝试使用 vue 方法生成 JSON object 并使用 vue 输入数据字段来构建 JSON2668CFDE63911ACC49 的一部分My input files accept a key and a value and i have two default values 'zone' and 'capping'.
我的输入文件接受一个键和一个值,我有两个默认值“区域”和“封顶”。 My goal is for the JSON object to be like:
我的目标是让 JSON object 像:
{
"zone":{
"capping":{
"duration": 300
}
}
}
But instead i get a JSON object like this:但相反,我得到一个 JSON object 像这样:
{
"zone":{
"capping":{
"values":[
{
"key":"duration",
"value":"300"
}
]
}
}
}
This is my vue method:这是我的Vue方法:
generateJson() {
const values = this.inputs
const loopedObj = values.forEach((item) => {
const val = {
...item
}
return val
})
console.log(values)
const jsonValues = {
zone: {
capping: {
values
}
}
}
console.log(JSON.stringify(jsonValues))
}
This is the Vue code for the input fields:这是输入字段的 Vue 代码:
<div>
<p>3- Add Data</p>
<button @click="showInput">+</button>
<div v-for="(input, k) in inputs" :key="k">
<input v-model="input.key" type="text" @change="getKey($event)" />
<input
v-model="input.value"
type="text"
@change="getValue($event)"
/>
</div>
Any advice?有什么建议吗? Many thanks.
非常感谢。
Looking at your template:查看您的模板:
<input v-model="input.key" type="text" @change="getKey($event)" />
<input
v-model="input.value"
type="text"
@change="getValue($event)"
/>
it looks like your input
is an object that has properties key
and value
:看起来您的
input
是具有属性key
和value
的 object :
inputs: [
{
key: "",
value: ""
}
]
When you did this:当你这样做时:
const values = this.inputs
const loopedObj = values.forEach((item) => {
const val = {
...item
}
return val
})
Problems are:问题是:
forEach
which just loops over the array.forEach
只是在数组上循环。 it won't return anything..map()
.map()
.map()
, what you did is just copy the object and so loopedObj
will stil look like this.inputs
..map()
,您所做的只是复制 object ,因此loopedObj
看起来像this.inputs
。 Almost the same as values.map((item) => item))
values.map((item) => item))
几乎相同And now when you did this:现在当你这样做时:
const jsonValues = {
zone: {
capping: {
values
}
}
}
It's as if you just did:就好像你刚刚做了:
const jsonValues = {
zone: {
capping: {
values: this.inputs
}
}
}
Because const values = this.inputs
never changed anywhere in your code.因为
const values = this.inputs
在代码中的任何地方都不会改变。 Never even tried to use loopedObj
as well.甚至从未尝试过使用
loopedObj
。
Solution:解决方案:
const values = {}
this.inputs.forEach((item) => {
values[item.key] = item.value
})
const json = {
zone: {
capping: values
}
}
Then maybe JSON.stringify()
it if you need it.然后如果你需要它,也许
JSON.stringify()
它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.