Reputation: 91
I am currently working on an assignment that has to do a lot with JS and JSON objects. I have my Javascript objects setup but I'm just curious as to how I would store two objects within one 'master' object and how I would output that data to the page.
Here is my code:
var javabook = {
"book": {
"isbn" : "0-596-00016-2",
"title" : "Java and XML",
"price" : "39.95",
"publisher" : "O'Reilly & Associates",
"copyright": "2000",
"authors": {
"author": {
"fname": "Brett",
"lname": "McLaughlin",
"price": "22.00"
}
}
}
};
var vb6book = {
"book": {
"isbn" : "1-861003-32-3",
"title" : "Professional Visual Basic 6 XML",
"price" : "49.99",
"publisher" : "Wrox Press",
"copyright": "2000",
"authors": [{
"fname": "James",
"lname": "Britt",
"price": ""
}, {
"fname": "Tuen",
"lname": "Duynstee",
"price": ""
}]
}
};
var myJSON = JSON.stringify(javabook);
var myJSON2 = JSON.stringify(vb6book);
var textbooks = [javabook, vb6book];
document.getElementById("demo").innerHTML = myJSON;
document.getElementById("demo2").innerHTML = myJSON2;
So what I am trying to do is store the two objects you see named 'javabook' and vr6book into one main object and then display them out to the page. So overall I need help getting these two JS objects into main object and then being able to access both separately and outputting them to the page with JSON stringify and then having them appear on the page. And with that how would this JS object translate to a basic JSON object? What I mean by that is apart from the questions I have about the JS how would my code look in standard JSON format since I am trying to learn more about it? Any help is appreciated, thanks!
Upvotes: 1
Views: 81
Reputation: 1057
var javabook = {
"book": {
"isbn" : "0-596-00016-2",
"title" : "Java and XML",
"price" : "39.95",
"publisher" : "O'Reilly & Associates",
"copyright": "2000",
"authors": {
"author": {
"fname": "Brett",
"lname": "McLaughlin",
"price": "22.00"
}
}
}
};
var vb6book = {
"book": {
"isbn" : "1-861003-32-3",
"title" : "Professional Visual Basic 6 XML",
"price" : "49.99",
"publisher" : "Wrox Press",
"copyright": "2000",
"authors": [{
"fname": "James",
"lname": "Britt",
"price": ""
}, {
"fname": "Tuen",
"lname": "Duynstee",
"price": ""
}]
}
};
var masterobject = {
javabook: javabook,
vb6book: vb6book
};
You then can access the object with:
var book1 = JSON.stringify(masterobject.javabook);
var book2 = JSON.stringify(masterobject.vb6book);
document.getElementById("demo").innerHTML = book1;
document.getElementById("demo2").innerHTML = book2;
Upvotes: 2
Reputation: 721
Var textbooks = [ ];
textbooks.push( javabook );
textbooks.push( vb6book );
console.log("Whole obj - -> ",textbooks)
Upvotes: 1