如何动态创建Javascript对象?

时间:2014-09-27 03:40:41

标签: javascript arrays json object

我正在尝试创建以下内容:

var deal_info = {
    "1": {
        "deal": {
            "deal_id": "1",
            "qty": "1",
            "option_price_sale": "7900",
            "price_ship": "2500",
            "ship_price_type": "1"
        }
    },
    "2": {
        "deal": {
            "deal_id": "2",
            "qty": "1",
            "option_price_sale": "3880",
            "price_ship": "2500",
            "ship_price_type": "1"
        }
    }
};

我从

开始
var deal_info = {};

如何动态继续创建数组?

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

这不是数组,即具有2个属性的对象

"1" : {                 
            "deal" : {
                "deal_id" : "1",                        
                "qty" : "1",
                "option_price_sale" : "7900",
                "price_ship" : "2500",
                "ship_price_type" : "1"                     
            }
        }

"2" : {
            "deal" : {
                "deal_id" : "2",                        
                "qty" : "1",
                "option_price_sale" : "3880",
                "price_ship" : "2500",
                "ship_price_type" : "1"                     
            }
        }

使它成为一个数组,它应该是

var deal_info = [
        {                 
            "deal" : {
                "deal_id" : "1",                        
                "qty" : "1",
                "option_price_sale" : "7900",
                "price_ship" : "2500",
                "ship_price_type" : "1"                     
            }
        },

        {
            "deal" : {
                "deal_id" : "2",                        
                "qty" : "1",
                "option_price_sale" : "3880",
                "price_ship" : "2500",
                "ship_price_type" : "1"                     
            }
        }
    ];

如前所述,您可以推送新对象,例如

deal_info.push({"3" : {
            "deal" : {
                "deal_id" : "3",                        
                "qty" : "1",
                "option_price_sale" : "3880",
                "price_ship" : "2500",
                "ship_price_type" : "1"                     
            }
        }});

答案 1 :(得分:1)

var deal_info = {};

deal_info["1"] = {};
deal_info["1"]["deal"] = {};