如何用第一个InvoiceNo的值不替换为第二个值的方式来表示此javascript对象定义?


  EDIT

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
                }
            }

最佳答案

您可以这样简单:

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 JSONLint进行验证。

JsFiddle demo

07-24 09:20