3
this.addToCart = function(id,name,category,price) {
    alert(id+"name"+name);

    var eachProduct = [
        {
            "name": name,
            "id": id,
            "category":category,
            "price":price
        }


    ];
    alert(eachProduct.name);//I am getting undefine
    addedProductsList.push(eachProduct);

    sessionStorage.setItem("addedProductsList", addedProductsList);

    return "success";
};

How to pass the function parameters to each product?

1
  • 1
    eachProduct is declared as an array, and you have one item in it. Try eachProduct[0].name. If you didn't intend 'eachProduct' to be an array, then remove the square brackets: []; then you can do eachProduct.name. Commented Jun 9, 2014 at 7:08

3 Answers 3

14

As Abdul has pointed out you have a JSON array and you want a JSON object, there you need

  var eachProduct = 
                     {
                         "name": name,
                         "id": id,
                         "category":category,
                         "price":price
                     };

Now alert(eachProduct.name); will return name. And I assume by "How to pass the function parameters to the each product" you mean add an attribute to your JSON object. To do this you you would have

eachProduct["someAttribute"]='"value":someValue';
Sign up to request clarification or add additional context in comments.

Comments

1

You have declared eachProduct as an array, you need to use eachProduct[0].name instead.

2 Comments

how to push eachProduct array into addedProductList array and how to retrieve it from the storage and get eachProduct name
did you try addedProductsList.push(eachProduct[0]);
1

You can use forEach to iterate through the array. Please find the jsFiddle working on your example.

Snippet of code:

eachProduct.forEach(function(obj){
  alert(obj.name);
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.