我是JSON的新手,面临创建一个非常简单的数组的问题。
我有从HTML表单收到的密钥,值对:
frm1 = {"fname":"John","lname":"Doe","location":"CA"};
frm2 = {"fname":"Jenny","lname":"Doe","location":"CA"};
我想创建一个如下所示的JSON:
{
"employee":[
{"fname":"John","lname":"Doe","location":"CA"},
{"fname":"Jenny","lname":"Doe","location":"CA"}
]}
仅通过以下代码尝试推送第一个表单数据(frm1
)无效。
var form1 = {"employee":[]};
form1.employee = frm1;
console.log(JSON.stringify(form1)); // prints form1 :{"employee" : ["fname","lname","location"]}
仅打印键。请建议。
答案 0 :(得分:2)
使用数组元素
创建对象
var frm1 = {
"fname": "John",
"lname": "Doe",
"location": "CA"
},
frm2 = {
"fname": "Jenny",
"lname": "Doe",
"location": "CA"
};
var form1 = {
"employee": [frm1, frm2]
};
console.log(JSON.stringify(form1));
push()
推送元素
var frm1 = {
"fname": "John",
"lname": "Doe",
"location": "CA"
},
frm2 = {
"fname": "Jenny",
"lname": "Doe",
"location": "CA"
};
var form1 = {
"employee": []
};
form1.employee.push(frm1,frm2);
console.log(JSON.stringify(form1));
答案 1 :(得分:2)
只需应用它们
var form1 = { employee: [frm1, frm2] };
答案 2 :(得分:0)
var frm1 = {"fname":"John","lname":"Doe","location":"CA"};
var frm2 = {"fname":"John","lname":"Doe","location":"CA"};
var form1 = {"employee":[" ",""]};
form1["employee"][0] = frm1;
form1["employee"][1] = frm2;
console.log(form1["employee"][0]);
console.log(form1);
console.log(JSON.stringify(form1));
由于键值是一个数组,你可以使用push或使用它的数组索引
抱歉,我误解了你想要一个具有多个值的数组用于员工
的单个对象的问题