I want to insert an object into an array which already has some object in it.

for example I have this object:

{"title": "Snow White", "page": 300}

and I want to add "book" with that object so that it would hold 3 object in it.

"bookmark": {
    "book": [
      {"title": "Cinderela", "page": 100},
      {"title": "Pinocchio", "page": 200}

How do I achieve this?

If I use this API:

.set(key, value)

I think it will remove the existing object and changed it with the new provided object.

Should I use:

.get(key, [defaultValue])

to get all objects in "book" and then add the new one along side the other objects before sending them back at once by using:


is there any simplest method than that?

Any help would be appreciate.

2 Answers

Shubham Khatri On Best Solutions

You can combine the get and set method to update the data

const book = store.get('bookmark.book');
const newBooks = [...(book || []), {"title": "Snow White", "page": 300}];
store.set('bookmark.book', newBooks);
Amaldev ps On

First you declare a object with bookmark and book as one of its property, then you can add any objects to this books array using push(), as below

let obj = {
            bookmark: {
               book : []

obj.bookmark.book.push({"title": "Cinderela", "page": 100});
obj.bookmark.book.push({"title": "Pinocchio", "page": 200});