var noOfChild=document.getElementById('btnInput').value;
for(var i=1;i<=noOfChild;i++){
createJSON();
function createJSON() {
alert('working')
var jsonObj =[];
var startId=1;
$("span[id=childNo]").each(function() {
var idChildName='childName'+startId;
var childName=document.getElementById(idChildName).value;
var idDobChild='dobChild'+startId;
var dobChild=document.getElementById(idDobChild).value;
var idSchoolName='schoolName'+startId;
var schoolName=document.getElementById(idSchoolName).value;
var idClassSection='classSection'+startId;
var classSection=document.getElementById(idClassSection).value;
alert(childName);
var item = {};
item ["child_name"] = childName;
item ["child_DOB"] = dobChild;
item ["child_class"] = classSection;
item ["child_school_name"] = "KV_32";
// jsonObj.push("{'"+startId+"':['"+item+"']}");
jsonObj.push(item);
startId=startId+1;
});
var obj={
"1":jsonObj
};
console.log(obj);
我想要这样的对象:
{"1":{"child_name": "ytfy", "child_DOB": "1993-06-18", "child_class": "d", "child_school_name": "KV_32"}}
但我是这样的:
1:{child_name: "ytfy", child_DOB: "1993-06-18", child_class: "d", child_school_name: "KV_32"}
答案 0 :(得分:1)
看起来您可能只是误读了console.log()
如果您尝试此代码:
var obj = {
'1': {
test: 'some data'
}
}
console.log(obj)
它将1: {test: "some data"}
输出到chrome dev工具控制台,但它位于可扩展的行Object
下方,表示该行实际上是对象的子键。因此,虽然控制台显示了这一点,但实际对象实际上看起来像:
{
'1': {
test: 'some data'
}
}
答案 1 :(得分:1)
var foo = { "oh" : "yeah" };
var bar = { "no" : "way" };
bar["foo"] = foo;
console.log(bar);
&#13;
答案 2 :(得分:1)
在我看来,这种实现方式更清晰,更好看。您唯一需要了解的是,通过调用objectResult["1"]
,您还可以创建一个字段“1”
var object = {"childName":"foo", "childSurname":"foo"};
var objectResult = {}
objectResult["1"] = object;
console.log(objectResult);