0

I have created my own method called pushLocalStorage() into my background.js to ease appending an object into an array of objects. It's purpose is to simply take data from the caller and if the key exists then push the data object onto the existing array stored in a previous iteration. If the key doesn't exist then create a new array indice.

The creation of the first object works fine. The second insertion successfully completed but insert the length of the array instead of the object. Finally the third and any subsequent inserts fail because the data is no longer an array but a string and my code verifies that the data is an array before inserting data. See example logging after the code:

Here's my code:

else if (request.method == 'pushLocalStorage')      
{
    var key; 
    var data;
    var stored;

    // if key isn't sent from caller, quit with error.
    if ( 'undefined' == typeof(request.key) )
    {
        sendResponse({success: 0,error: 'Key value was not sent from caller.'});
    }

    // if the key isn't a string type then quit with error.
    if ( 'string' != typeof(request.key) )
    {
        sendResponse({success: 0,error: 'Expected key passed from caller to be a ' + 
                                        'string but it was a(n) ' + typeof(request.key) + ' instead'});
    }

    // if data value isn't sent from caller, quit with error.
    if ( 'undefined' == typeof(request.data) )
    {
        sendResponse({success: 0,error: 'Data value was not sent from caller.'});
    }

    key    = request.key;
    data   = request.data;
    stored = localStorage.getItem(key); // attempt to retrieve existing store named by 'key'

    // Now if stored isn't null or undefined...
    if ( 'undefined' != typeof(stored) && stored != null )
    {
        // parse it back into a valid data structure from JSON
        stored = JSON.parse(stored);

        // if stored exists (should be an Array object)
        if ( stored.length )
        {
            // stored should be an array of objects so...
            for ( var i = 0 ; stored.length < i ; i++ )
            {
                // make sure not to push dupe tickets into the array. In this case, replace
                // the existing ticket with the new.
                if ( data.id === stored[i].id )
                {
                    stored[i] = data;

                    // save the data to localStorage (do not push but overwrite)
                    localStorage.setItem(key,JSON.stringify(stored));
                    test = JSON.parse(localStorage.getItem(key));
                    sendResponse({success: 1,data: test});
                    return;
                }
            }

            // save the stored object back to localStorage after pushing the new data to it.
            localStorage.setItem(key,stored.push(JSON.stringify(data)));
            test = JSON.parse(localStorage.getItem(key));
            sendResponse({success: 1,data: test});
        }
        else
        {
            console.log(' data would be: %o and stored was: %o', data,stored);
            sendResponse({success: 0, error: 'Attempt to coerce object into array not allowed.'});
        }
    }
    else
    {
        console.debug(' Creating new array to be stored.');
        stored = new Array(data);
        stored = JSON.stringify(stored);

        localStorage.setItem(key,stored);

        test = localStorage.getItem(key);
        test = JSON.parse(test);
        console.log('setItem.' + key + ',' + stored + '\nThe stored obj was: %o and the localStored.getItem after storage was: %o',test,localStorage.getItem(key));
        sendResponse({success: 1,data: test});
    }
}

In the chrome console I get the following:

Object  
localstorage push! [Object]:  
Object
localstorage push! [Object]:
Object
localstorage push! [Object]:
Object
localstorage push! [Object]:
Object
localstorage push! 2:  
Object
localstorage push! [Object]: 
Object
localstorage push! 2:
Object
localstorage push failed: Attempt to coerce object into array not allowed. 
Object
localstorage push failed: Attempt to coerce object into array not allowed.
Object
localstorage push! [Object]:
Object
localstorage push! 2:
Object
localstorage push failed: Attempt to coerce object into array not allowed.

So after trying several different methods of coding the functionality I desire, nothing seems to work. Am I barking up the wrong tree or am I just coding a poor implementation?

TIA

EDIT:

Fixed code in completion:

if (request.method == 'pushLocalStorage')       
{
    var key; 
    var data;
    var stored;

    // if key isn't sent from caller, quit with error.
    if ( 'undefined' == typeof(request.key) )
    {
        sendResponse({success: 0,error: 'Key value was not sent from caller.'});
    }

    // if the key isn't a string type then quit with error.
    if ( 'string' != typeof(request.key) )
    {
        sendResponse({success: 0,error: 'Expected key passed from caller to be a ' + 
                                        'string but it was a(n) ' + typeof(request.key) + ' instead'});
    }

    // if data value isn't sent from caller, quit with error.
    if ( 'undefined' == typeof(request.data) )
    {
        sendResponse({success: 0,error: 'Data value was not sent from caller.'});
    }

    key    = request.key;
    data   = request.data;
    stored = localStorage.getItem(key); // attempt to retrieve existing store named by 'key'

    // Now if stored isn't null or undefined...
    if ( 'undefined' != typeof(stored) && stored != null )
    {
        // parse it back into a valid data structure from JSON
        stored = JSON.parse(stored);

        // if stored exists (should be an Array object)
        if ( stored.length )
        {
            // stored should be an array of objects so...
            for ( var i = 0 ; i < stored.length ; i++ )
            {
                // make sure not to push dupe tickets into the array. In this case, replace
                // the existing ticket with the new.
                if ( data.id === stored[i].id )
                {
                    stored[i] = data;

                    // purge the item...
                    localStorage.removeItem(key);

                    // save the data to localStorage.
                    localStorage.setItem(key,JSON.stringify(stored));

                    data = JSON.parse(localStorage.getItem(key));
                    sendResponse({success: 1,data: data});
                    return;
                }
            }

            // save the stored object back to localStorage after pushing the new data to it.
            stored.push(data);
            localStorage.setItem(key,JSON.stringify(stored));
            data = JSON.parse(localStorage.getItem(key));
            sendResponse({success: 1,data: data});
        }
        else
        {
            sendResponse({success: 0, error: 'Attempt to coerce object into array not allowed.'});
        }
    }
4

1 回答 1

0

好吧。弄清楚了。当我应该走动的时候,我却在走动:

错误的:

localStorage.setItem(key,stored.push(JSON.stringify(data)));

正确的:

stored.push(data);
localStorage.setItem(key,JSON.stringify(stored));

test = JSON.parse(localStorage.getItem(key));
sendResponse({success: 1,data: test});

问题是我试图将一个字符串化的值推送到一个数组对象中。是的,不能那样做。一旦我解决了这个问题,一切都很好。

于 2012-07-24T01:08:53.667 回答