-1
var cartArray = [];
//in a loop
    var cartObject = {};
    cartObject.item_name = 'NAME';
    cartObject.quantity = number;
    cartObject.amount =  number;
    cartObject.total = cart.amount * cart.quantity;
    cartObject.subtotal = cart.subtotal + cart.total;
    // store
cartArray[i]=cartObject;

can we directly store like on the fly without having full information of cartObject

var cartArray=[]
cartArray[i].item_name ='NAME'
cartArray[i].quantity =number

this thing works like

var cartArray=[]
cartArray[i]={}// it needs to be defined for each i
cartArray[i].item_name ='NAME'
cartArray[i].quantity =number

can we bypass this thing

7
  • 1
    Only if you created the object before. Commented Jul 22, 2020 at 15:03
  • 1
    Why not use cartArray[i] = {item_name: 'NAME', quantity: number, …};? Commented Jul 22, 2020 at 15:04
  • I don't have all the information of object, and I want to store in property if required. Like at some point I want to have added new property like "discount" in array index n. to store new property Commented Jul 22, 2020 at 15:16
  • Yes, you can add properties to an object at any time. But the object must already exist in the array for a cartArray[i].discount = number assignment to succeed. If you did create the objects in the first loop, and then afterwards add a new .discount property to them, it will work just fine. Did you try it? Commented Jul 22, 2020 at 15:18
  • 2
    (I would however recommend that you create the objects with all their properties initially, and keep their values undefined until the point where you get the information). Commented Jul 22, 2020 at 15:20

2 Answers 2

1

Here is what you want:

var cartArray = [];
//in a loop
cartArray[i] = {
    item_name: 'NAME',
    quantity: number,
    amount: number,
    total: cart.amount * cart.quantity,
    subtotal = cart.subtotal + cart.total
}

Sign up to request clarification or add additional context in comments.

Comments

1

I want to update G[2].mobileVar=1233 but I don't know if I have defined the object already

In that case, you can write

if (!G[2]) G[2] = {};
G[2].mobileVar = 1233;

to create the object only if it does not already exist in the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.