0

I know this question will seem to be a very common problem, but trust me I've spent hours searching on Google before asking this question...

I have some data looking like this :

- book1
----- book1 number of pages
----- book1 number of chapters
----- book1 author
- book2
----- book2 number of pages
----- book2 number of chapters
----- book2 author

First question : how should I do ?

I've thought about :

let books_collection = {
 "book 1":
    {
      "number_of_page": 100,
      "number_of_chapters": 5,
      "author": "Author 1"
    },

 "book 2":
    {
      "number_of_page": 200,
      "number_of_chapters": 7,
      "author": "Author 2"
    }
}

Does it looks good to you ? I will need to search easily into those data and save it to a Json file

 

Second question : how can I add a new book to this list?

When I search on Google, I find a lot of tutorials on how to add element to an ARRAY, but not to a list like that...

How to add a new "book 3" to this list ?

 

Third question : how can I add a new subcategory to a book in this list?

If I want to create a new subcategory, like "original_title" , to an existing book, how to do that ?

Thanks a LOT guys :)

Tsar Buig
  • 13
  • 4
  • You can simply do `books_collection.newBook = { "number_of_page": 1, "number_of_chapters": 2, "author": "foo"}` or `books_collection["new Book"] = { "number_of_page": 1, "number_of_chapters": 2, "author": "foo"}` depending on whether you want to allow spaces in the object key (I would advise against it) – secan Sep 09 '22 at 14:51
  • Sorry, I misread your question; to add a new key to an existing book you can do `books_collection["book 3"].original_title = "blablabla"` – secan Sep 09 '22 at 14:53
  • bro I have another stupid problem when I try to apply your first comment... In my software, "newBook" is a variable who contains the book's name. But when I try to write your code : ```books_collection.newBook = { "number_of_page": 1, "number_of_chapters": 2, "author": "foo"}``` then it writes the "newBook" word in my list, instead of using the variable value (like "War and Peace") --> how can I use real title in the list ? – Tsar Buig Sep 09 '22 at 19:05
  • Have a look at [this question](/q/1184123) – cachius Sep 09 '22 at 20:52
  • Then you have to use the bracket notation (`books_collection[yourVariableName]`), instead of the dot notation (`books_collection.newBook`) – secan Sep 10 '22 at 21:10

1 Answers1

0
let book3 = {
  "book 3": {
    /*properties*/
  }
}

Object.assign(books_collection, book3)

how to add new subcategories: call Object.assign for every book in a loop

let original_title = {
  "original_title": "something"
}

for (let book of Object.values(books_collection) {
  Object.assign(book, original_title)
}
Aziz Hakberdiev
  • 180
  • 2
  • 9