I’m moving items from one array to another as long as it doesn’t already exist, then storing that in localStorage
var queue = [];
function moveToQueue(item) {
if(queue.indexOf(item) == -1) {
queue.push(item);
store();
}
}
function store() {
localStorage.myApp_queue = JSON.stringify(queue);
}
When the page loads, I call my load function.
function load() {
if(typeof localStorage.myApp_queue != 'undefined') {
queue = JSON.parse(localStorage.myApp_queue);
}
}
At this point, my interface shows the queue as I had last left it, but if I try to add the same item again, the “queue.indexOf(item)” is failing. The contents of queue is not the same as it was before the store()/load() methods were called.
Here are some console.log() calls before and after my page reload, starting with an empty queue. The logs have been added to the start of the moveToQueue function
function moveToQueue(item) {
console.log('adding to queue');
console.log(item);
console.log(queue[0]);
console.log(queue.indexOf(item));
...
Initial load:
adding to queue
e {id: 1, status: "A", title: "Comcar", $$hashKey: "004", $get: function…}
undefined
-1
adding to queue
e {id: 1, status: "A", title: "Comcar", $$hashKey: "004", $get: function…}
e {id: 1, status: "A", title: "Comcar", $$hashKey: "004", $get: function…}
0
After page refresh – the Item I’m pushing is already in the queue array
adding to queue
e {id: 1, status: "A", title: "Comcar", $$hashKey: "006", $get: function…}
Object {id: 1, status: "A", title: "Comcar", $$hashKey: "004"}
-1
What have I missed here, what is localStorage and JSON doing to change my array.
I can see the log lists the item returned from storage as “Object”, whereas the original item has a “type” (not quite sure about that) of “e”.
If I use typeof the result for both is “object”
It does not change your array (your old one was lost when unloading the page). It creates a totally new one, with totally new item objects. If you now create items that look exactly like those you already have, they are still two distinct objects and comparing them by reference (as
indexOfwith===does) will yieldfalse.So either you will need to change your construction function that no new ones are built but old ones are reused, or you will need to use a special comparison function that tells object equality by their ids for example.