Mustapha George
Mustapha George

Reputation: 2527

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

Upvotes: 0

Views: 113

Answers (3)

Bakudan
Bakudan

Reputation: 19492

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

Upvotes: 0

Wayne
Wayne

Reputation: 60414

You don't need to define any invoices at the time myObject is initialized. You can dynamically add them later:

var myObject = { 
    invoices: []
}

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

Upvotes: 1

user1106925
user1106925

Reputation:

Far as I can tell, you're looking for this...

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

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

Or this...

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

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

Upvotes: 1

Related Questions