Nitish Jaiswal
Nitish Jaiswal

Reputation: 15

How to put object inside another object using javascript

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);

I want object like this:

{"1":{"child_name": "ytfy", "child_DOB": "1993-06-18", "child_class": "d", "child_school_name": "KV_32"}}

But i am getting like this:

1:{child_name: "ytfy", child_DOB: "1993-06-18", child_class: "d", child_school_name: "KV_32"}

Upvotes: 0

Views: 70

Answers (3)

mcsilvio
mcsilvio

Reputation: 1098

var foo = { "oh" : "yeah" };
var bar = { "no" : "way" };
bar["foo"] = foo;
console.log(bar);

Upvotes: 1

Eugenio
Eugenio

Reputation: 1053

This implementation in my opinion is a lot cleaner and nicer to see. The only thing you have to understand is that by calling objectResult["1"] you also create a field "1"

var object = {"childName":"foo", "childSurname":"foo"};
var objectResult = {}

objectResult["1"] = object;
console.log(objectResult);

Upvotes: 1

Matt Way
Matt Way

Reputation: 33179

It looks like you might be simply misreading console.log()

If you try this code:

var obj = {
  '1': {
    test: 'some data'
  }
}

console.log(obj)

It outputs 1: {test: "some data"} to the chrome dev tools console, however it sits below an expandable line that says Object, indicating that the line is in fact a child key of an object. So while the console shows this, the actual object does in fact look like:

{
  '1': {
    test: 'some data'
  }
}

Upvotes: 1

Related Questions