简体   繁体   English

从JSON数组的内容创建带有原型函数的JavaScript对象

[英]Create JavaScript objects with prototype functions from contents of JSON array

I have a JSON structure; 我有一个JSON结构;

{ 
  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? 在BookList中创建Book对象数组的最佳方法是什么?

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. 使用jQuery,您可以仅使用$.parseJSON(jsonData).books来分配BookList数组并自动具有属性值,但不会使用原型函数创建所需的对象。

Is the only way to iterate over the JSON array and create each Book object individually? 是遍历JSON数组并单独创建每个Book对象的唯一方法吗? This question covers creating a particular prototyped object from JSON: Parse JSON String into a Particular Object Prototype in JavaScript . 这个问题涉及从JSON创建特定的原型对象:将JSON字符串解析为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. 我认为这可以扩展到适用于具有正确迭代级别的BookList,并从那里适用于Book对象的章节。

Is it possible to change an object type after initial assignment with $.parseJSON ? 使用$.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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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