how to reformat this javascript array? -
i have variable this
var item = [ {'id': '1', 'quantity': '100'}, {'id': '2', 'quantity': '200'} ];
but need change format
var new_item = { '1': {'quantity': '100'}, '2': {'quantity': '200'} };
i loop this, errors
for(i=0; i<item.length; i++){ new_item = { item[i].id: {'quantity': item[i].quantity} }; }
how can change format t__t
update fix:
oh yes need change this
for(i=0; i<item.length; i++){ new_item[item[i].id] = {'quantity': item[i].quantity}; }
that work, sorry damn question, think i'm sleepy, thx guys ^_^
you need use bracket notation set derived keys. initialize new_item = {}
first.
new_item[item[i].id] = {quantity: item[i].quantity}
note if using ecmascript6 can use computed property names in object initializers so;
new_item = { [item[i].id]: {quantity: item[i].quantity} }
however, overwrites new_item
each time have last value of array.
Comments
Post a Comment