jayendra bhatt jayendra bhatt - 2 months ago 7
AngularJS Question

Unable to add data to an array taken out from a cookie

Am not able to add data to an array taken out from a cookie .

var x1 =[];
if($cookies.get(uid )== undefined)
{
var arr =[];
arr.push($scope.stock);
$cookies.put("arr",JSON.stringify(arr));
$cookies.put("uid","xxx");
console.log("==uid not found in cookie in angular --- cookies.uid"+ $cookies.get("arr"));
}
else
{
console.log("inside else"+JSON.stringify($cookies.getObject("arr"))); // gives output ["bse:yesbank"]
x1= JSON.stringify($cookies.getObject("arr"));
----> console.log(x1 instanceof Array); // returns false
----> x1.push($scope.stock);

}


it gives
x1.push is not a function

Moreover, it's says the
JSON.stringify($cookies.getObject("arr"))
is not an array but the value of above expression is
["bse:yesbank"]
which is nothing but an array. please correct me where I am getting wrong .

Answer

That is because you use JSON.stringify, wich turns the array into a string looking like the array.

Try to get the value without stringify:

x1= JSON.stringify(["test"]);
console.log(x1 instanceof Array); // returns false 

console.log(JSON.parse(x1) instanceof Array); // returns true

Comments