Search code examples
jqueryarrayshtmllocal-storageextend

jQuery extend overwrites part of array


I am creating a Google Chrome User Script, which will store users usernames that a user has selected to ignore. All ignored users will be stored locally using the HTML5 Local Storage API.

I am using jQuery to help add users to a JSON array, which will then be stored locally. My problem is that it always overwrites the first item.

If I add "testuser1", then try to add "testuser2" it will store the details for "testuser2" and "testuser1" will have disappeared.

// Get users from localstorage
var ignored_users = JSON.parse(localStorage.getItem("ignore_list"));

// If NULL, prepare as JSON
if(ignored_users === null)
{
    var ignored_users = {};
}

// Prep
var username = get_username_profile();
desc = prompt("Why do you want to ignore this user?");

// Add to list
add_to_list = [{
    "username" : username,
    "description" : desc
}];
$.extend(ignored_users, add_to_list);
localStorage["ignore_list"] = JSON.stringify(ignored_users);

// Highlight as ignored
$(".user_wrapper").css("background-color","#B40404");

Solution

  • ignored_users is an object that contains an array (you should rather make it an array, unless you want to store extra info in the object), which you are overwriting, so your behavior is expected, what you should do is retrieve the array, and push the extra object onto it:

    var ignored_users = JSON.parse(localStorage.getItem('ignore_list'));
    if (!ignored_users) {
        ignored_users = [];
    }
    
    var username = get_username_profile();
    desc = prompt("Why do you want to ignore this user?");
    
    var add_to_list = {
        "username" : username,
        "description" : desc
    };
    
    ignored_users.push(add_to_list);
    localStorage['ignore_list'] = JSON.stringify(ignored_users);
    

    PS: no checks are done for duplicate ignored users, you should probably do that :)