I can not understand how to add key / value to an array. It is necessary to have an array of objects in localStorage, but it is impossible to screw the id to the book object. Help me please!

import UUIDv4 from 'uuid/v4'; function addBook(authorBook, nameBook, yearBook, imageSRC) { const id = UUIDv4(); let book = { author: authorBook, name: nameBook, year: yearBook, imageSRC: imageSRC }; let books = []; let key = id; books.unshift({ key: book }); let parseBook = JSON.stringify(books); return localStorage.setItem('SAVED_BOOK', parseBook); } 

    2 answers 2

    For storing data in the format key => value in javascript there is a data type Map . Detailed usage documentation.

    If you need full browser support, look at the solution below, to iterate over the object, you can study this comment .

    Also note localStorage.getItem('SAVED_BOOK') , if you want to save several books, first you need to get a value from localStorage

     import UUIDv4 from 'uuid/v4'; function addBook(authorBook, nameBook, yearBook, imageSRC) { const id = UUIDv4(); let books = localStorage.getItem('SAVED_BOOK'); if (!books) { books = {}; } else { books = JSON.parse(books); } books[id] = { author: authorBook, name: nameBook, year: yearBook, imageSRC: imageSRC }; let parseBook = JSON.stringify(books); return localStorage.setItem('SAVED_BOOK', parseBook); } 

      In order to add a field with the value of the key variable to the object instead of the property named key , you can use the notation for the calculated properties

       books.unshift({[key]:book});