how to create json object in angular js

Nikhila Benjaram picture Nikhila Benjaram · Jun 9, 2014 · Viewed 86.3k times · Source
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?

Answer

Ronald91 picture Ronald91 · Jun 9, 2014

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';