Reputation: 4167
In my angular app I'm trying to save/retrieve data between pages and have have the following function in place:
$scope.storeData = function () {
var selections = $scope.devices;
console.log(selections);
sessionStorage.setItem('selectedHandsets', JSON.stringify(selections));
var ss = sessionStorage.getItem('selectedHandsets');
console.log(ss);
}
The issue is quite strange. The key values that I'm after in selections
are 'selectedManufacturer' and 'selectedModel' and these values are displaying as expected in console.log(selections)
.
When ss
is logged, 'selectedManufacturer' and 'selectedModel' aren't visible in sessionStorage.selectedHandsets
. They're there when the data is being set because we can see it in selections but when I log ss
, they're gone!
The format of selections
is like so:
[
[
{ ... },
{ ... },
selectedModel: { ... },
selectedManufacuterer: { ... }
],
[
{ ... },
{ ... },
selectedModel: { ... },
selectedManufacuterer: { ... }
]
]
If I wrap JSON.stringify()
around console.log(selections)
then selectedModel and selectedManufacturer are disappearing. Could somebody explain to me exactly why this is happening and what the appropriate fix is?
Upvotes: 1
Views: 79
Reputation: 365
Have you tried checking the console if it throws an error?
What you have is a malformed JSON
[
[
{ ... },
{ ... },
selectedModel: { ... },
selectedManufacuterer: { ... }
],
[
{ ... },
{ ... },
selectedModel: { ... },
selectedManufacuterer: { ... }
]
]
Look at
[
{ ... },
{ ... },
selectedModel: { ... }, //There shouldn't be a named item in an array here
selectedManufacuterer: { ... } //There shouldn't be a named item in an array here
]
There shouldn't be a named object in an array.
EDITS
What you did was like this:
var arrayBuff= [];
arrayBuff.push(2);
arrayBuff.push(4);
arrayBuff.push(6);
//this would produce this: [2,4,6]
console.log(arrayBuff);
arrayBuff.someField = "foobar";
//this would produce this: [2,4,6, someField: "foobar"]
// which is a malformed array
console.log(arrayBuff);
You can do this instead:
var arrayBuff = {},
arrayBuff.arrays = [];
arrayBuff.arrays.push(2);
arrayBuff.arrays.push(4);
arrayBuff.arrays.push(6);
//this would produce this: { arrays: [2,4,6] }
console.log(arrayBuff);
arrayBuff.someField = "foobar";
//this would produce this: { arrays: [2,4,6], someField: "foobar"}
// which is correct and can be parsed by JSON.stringify
console.log(arrayBuff);
The reason why the JSON.stringify wasn't been able to parsed the named field was, simply because it was expecting an array.
Upvotes: 2
Reputation: 116
The previous answer is right. What you can do is reconstruct your selections to be an object like { arrObjs : [ your array will be here], models: [...], manufacturers:[...] }
Upvotes: 0