metersk
metersk

Reputation: 12509

Appending to an object in a list of objects

I have a javascript array that contains objects and looks like this:

[{‘sku':’ASD',’price': 10.99,’name':’Hot Sauce',’quantity': 1}, {‘sku':’JKL',’price': 8.99,’name':’Chilli Peppers',’quantity': 1}, {‘sku':’UIO',’price':’10.50',’name': "Sip 'n' Sizzle T-Shirt",’quantity': 1}]

I have a variable that contains the subtotal for the entire order and I would like to append it to each object for database purposes.

I tried this, but it messed everything up.:

var allProdData = prodData.push({total: total})

I assume I have to a use a for loop, but I'm not quite sure how to do it.

Upvotes: 0

Views: 1103

Answers (2)

jhyap
jhyap

Reputation: 3837

First give a correct format for your array like below:

var arr = [{sku:'ASD',price: 10.99,name:'Hot Sauce',quantity: 1}, ...]

Then loop the array, calculate the total and format a new array

var arrNew = [];


for (var i  = 0; i < arr.length; i++){

    var total = arr[i].price * arr[i].quality;
    arrNew.push({sku:arr[i].sku,price: arr[i].price,name:arr[i].name,quantity: arr[i].quality, total:total});
}

Upvotes: 2

Nic
Nic

Reputation: 2843

I had the same problem a couple of days ago try this

for(key in Objectname){
    var allProdData = prodData.push(Objectname[key].total)
}

Put the correct objectname

Upvotes: 3

Related Questions