I wish to add wishlist functionality to a client site using a combination of Javascript and cookies. To achieve this, each item on the site will have a button that the user can click to add the item to their wishlist. The button code is as follows:
<a data-id="5054" data-node="3286" data-type="package" class="wishList">Add to Wishlist</a>
When the button is clicked the following JavaScript is executed:
$('.wishList').click(function () {
var nodeId = $(this).data("node");
var id = $(this).data("id");
var type = $(this).data("type");
var package = new Object();
package.id = id;
package.nodeId = nodeId;
var jsonObject = new Object();
jsonObject.package = package;
var jsonString = JSON.stringify(jsonObject);
console.log(jsonString);
var newObject = new Object();
newObject.id = 8888;
newObject.nodeId = 7777;
var obj = JSON.parse(jsonString);
obj['package'].push(newObject);
console.log(JSON.stringify(obj));
});
This code is derived from this Stack Overflow question and my own knowledge:
Adding a new array element to a JSON object
The aim of the code is to simulate both creating a new JSON notation using Javascript objects as well as parsing the notation back into a Javascript object, adding a new item to the array and then using stringify to convert it back into a string again. My problem is, the push method does not seem to work. When I run this code, I get the following error:
TypeError: obj.package.push is not a function
As this part of the code was taken from the other question, I am at a loss to understand why it is not working in this context as I do not see any comments suggesting that this does not work on the other post.
My aim is to build up the following JSON notation:
{"package":[{"id":"5054","nodeId":"3286"},{"id":"8888","nodeId":"7777"}]}
This will eventually lead to a more complex notation of:
{"package":[{"id":"5054","nodeId":"3286"},{"id":"8888","nodeId":"7777"}], "hotel":[{"id":"3421","nodeId":"1234"},{"id":"8748","nodeId":"2435"}],}
This notation will then be stored as a cookie that will be added to and manipulated using JavaScript and read on the server side with each request using .Net.
My question is, what am I doing wrong here? Why in this case is the .push funcionality not working?
I've created a Fiddle here: http://jsfiddle.net/jezzipin/kdVVK/