如何在角度js中创建json对象

Nik*_*ram 3 javascript json function-parameter angularjs

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";
};
Run Code Online (Sandbox Code Playgroud)

如何将功能参数传递给每个产品?

Ron*_*d91 14

正如Abdul已经指出你有一个JSON数组而你想要一个JSON对象,你需要它

  var eachProduct = 
                     {
                         "name": name,
                         "id": id,
                         "category":category,
                         "price":price
                     };
Run Code Online (Sandbox Code Playgroud)

现在alert(eachProduct.name);将返回名称.我假设"如何将函数参数传递给每个产品"是指向JSON对象添加属性.你要做到这一点

eachProduct["someAttribute"]='"value":someValue';
Run Code Online (Sandbox Code Playgroud)