定义javascript对象属性

时间:2011-12-27 22:56:45

标签: javascript object entities

如何以第一个InvoiceNo的值不被第二个值替换的方式表达这个javascript对象定义?

  

编辑<最终,我想要一个名为myObject的对象,其中包含一个Invoice数字数组。每张发票号码都有相关的账单和发货号码......

var myObject = {};

myObject = { "InvoiceNo" : 44444, 
             "Shipping":
                {
                    "ShipTo": 22345 , "BillTo": 43456 
                }
            }

// some more code here that would capture user input or a data from a remote data feed...

myObject = { "InvoiceNo" : 555555, 
             "Shipping":
                {
                    "ShipTo": 32345 , "BillTo": 33456 
                }
            }

3 个答案:

答案 0 :(得分:1)

我可以告诉你,你正在寻找这个......

var myObject = { 
    "44444": {"ShipTo": 22345 , "BillTo": 43456 },
    "555555":{"ShipTo": 32345 , "BillTo": 33456 }
};

myObject[ "777777" ] = {"ShipTo": 88888 , "BillTo": 99999 }

或者这......

var myObject = { 
    "invoices": [
         {"invoice":"44444", "ShipTo": 22345 , "BillTo": 43456 },
         {"invoice":"555555", "ShipTo": 32345 , "BillTo": 33456 }
    ]
};

myObject.invoices.push( {"invoice":"777777", "ShipTo": 88888 , "BillTo": 99999 } )

答案 1 :(得分:1)

初始化myObject时,您无需定义任何发票。您可以稍后动态添加它们:

var myObject = { 
    invoices: []
}

myObject.invoices.push({"invoice":"44444", "ShipTo": 22345 , "BillTo": 43456 });
myObject.invoices.push({"invoice":"555555", "ShipTo": 32345 , "BillTo": 33456 });

答案 2 :(得分:0)

你可以做这样简单的事情:

var myObject = [
    {
        "InvoiceNo": 44444,
        "Shipping": { "ShipTo": 22345, "BillTo": 43456 }
    },
    {
        "InvoiceNo": 555555,
        "Shipping": { "ShipTo": 32345, "BillTo": 33456 }
    }
];
console.log(myObject[0].InvoiceNo); // 0 - the first object inside the array
console.log(myObject[0].Shipping.ShipTo); // access the "ShipTo" property of the first element

要进行更复杂的JSON WikipediaJSONLint验证。

JsFiddle demo