grevory/angular-local-storage

How to add / push new json object?

onigetoc opened this issue · 4 comments

How to add / push new json object?
{"fName":"7abc","lName":"7pqr","email":"7abc@pqr.com"}

i guess it will look like this in localStorage
[{"fName":"7abc","lName":"7pqr","email":"7abc@pqr.com"},{"fName":"8abc","lName":"8pqr","email":"8abc@pqr.com"},{"fName":"9abc","lName":"9pqr","email":"9abc@pqr.com"}]

Also adding only after checking if it's already exist or not.

Hi, i read all but do not understand yet how to push another json object to a already existing localstorage key.
i am building my own localStorage factory based on this one.
https://gist.github.com/Alexintosh/8e8dd716860c8fdcd08a

i'm adding my own $localstorage.add

    add: function (key, value, ID, max ) {
    
    var getstorage = [];
    getstorage = JSON.parse($window.localStorage.getItem(key)) || [];

    if (max && getstorage.length >= max )
      getstorage.splice(-1,1); // REMOVE LAST OBJECT
    
      // if exist (TO DO)
//        var addToArray = true;
//        for (var i = 0; i < getstorage.length; i++) {
//            if (getstorage[i].ID === ID) {
//                addToArray = false;
//            }
//        }
//        if (addToArray) {
//        getstorage.reverse().push(value);
//
//        } else {
//
//            for (i = 0; i < getstorage.length; i++) {
//                if (getstorage[i].ID == ID) getstorage.splice(i, 1);
//            }
//
//
//        }
      
    //reverse order to push last
    getstorage.reverse().push(value);
      
    // Push the new data (whether it be an object or anything else) onto the array
    //getstorage.push(value);
    //reverse order to make last item first
    getstorage.reverse();

    $window.localStorage.setItem(key, angular.toJson(getstorage));
    },

ID: will be the json key to check if it exist
max : will be the max of items to add. like no more than 20 items in my localStorage.

This sounds like an implementation that should exist outside of this module.

// If the value of "myUsers" is [{"fName":"7abc","lName":"7pqr","email":"7abc@pqr.com"}] let lsData = (localStorageService.get('myUsers') || []).slice(); lsData.push({"fName":"8abc","lName":"8pqr","email":"8abc@pqr.com"}); lsData.push({"fName":"9abc","lName":"9pqr","email":"9abc@pqr.com"}); localStorageService.set('myUsers', lsData);

Maybe you could write a function in your app to handle your special case.

Hi, i did my own simple Localstorage factory and it work well, will make it better on the run.