简体   繁体   中英

Create JavaScript objects with prototype functions from contents of JSON array

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM