up vote 2 down vote favorite
share [g+] share [fb]

I have a JSON structure;

{ 
  books: [ 
    {"id": "book1", "title": "Book One"}, 
    {"id": "book2", "title": "Book Two"} 
  ] 
}

Which represents;

function BookList() {
    this.books = new Array();
}

BookList.prototype.addBook = function(b) {
    this.books[this.books.length] = b;
}

function Book(id, title) {
    this.id = id || '';
    this.title = title || '';
    this.chapters = new Array();
}

Book.prototype.addChapter = function(c) {
    this.chapters[this.chapters.length] = c;
}

What is the best way to create the array of Book objects within the BookList?

With jQuery you can just use $.parseJSON(jsonData).books to assign the BookList array and have the properties values automatically but that doesn't create the required objects with the prototype functions.

Is the only way to iterate over the JSON array and create each Book object individually? This question covers creating a particular prototyped object from JSON: Parse JSON String into a Particular Object Prototype in JavaScript.

I supposed this could be extended to apply to the BookList with the right level of iteration and from there applied to the chapters for the Book object.

Is it possible to change an object type after initial assignment with $.parseJSON?

link|improve this question

feedback

1 Answer

up vote 1 down vote accepted
var json = { 
  books: [ 
    {"id": "book1", "title": "Book One"}, 
    {"id": "book2", "title": "Book Two"} 
  ] 
};

var list = new BookList();
list.books = json.books.map(convertToBook);

function convertToBook(book) {
  return new Book(book.id, book.title);
}
link|improve this answer
I've tried to find more info on .map but haven't found anything useful. Is there a resource you know of? Works really well as there is plenty of scope within the function call. The object I'm using has a lot more properties than the example so I just used return $.extend(new Book(), json); which provided I don't mess up the property names works well. Thanks. – Dave Anderson Jan 13 at 2:34
map – Raynos Jan 13 at 10:59
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.