Search code examples
javascriptobjectentities

defining a javascript object properties


How can express this javascript object defintion in a way that value of first InvoiceNo does not get replaced with second value?

EDIT< Ultimately i want an object called myObject that contains an array of Invoice numbers. Each invoice number would have a related bill and ship number...

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

Solution

  • You could make something simple like this:

    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
    

    For something more complicated JSON Wikipedia and JSONLint to validate.

    JsFiddle demo