0

i have variable like this

var item = [
            {'id': '1', 'quantity': '100'},
            {'id': '2', 'quantity': '200'}
        ];

but i need to change like this format

var new_item = {
            '1': {'quantity': '100'},
            '2': {'quantity': '200'}
        };

i do loop like this, but errors

for(i=0; i<item.length; i++){
            new_item = {
                item[i].id: {'quantity': item[i].quantity}
            };
        }

how can i change this format T__T

UPDATE FIX:

oh yes i just need to change like this

for(i=0; i<item.length; i++){
            new_item[item[i].id] = {'quantity': item[i].quantity};
        }

that work, sorry for my damn question, i think i'm too sleepy, thx guys ^_^

Donny Gunawan
  • 167
  • 1
  • 1
  • 7

3 Answers3

2

You need to use bracket notation to set derived keys. Initialize new_item = {} first.

new_item[item[i].id] = {quantity: item[i].quantity}

Note that if you were using ECMAScript6 you can use computed property names in object initializers like so;

new_item = {
    [item[i].id]: {quantity: item[i].quantity}
}

However, this overwrites new_item each time so it would ultimately only have the last value of the array.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
1
for(i=0; i<item.length; i++){
    new_item[item[i].id] = {'quantity': item[i].quantity};
}
Yavor Ivanov
  • 119
  • 3
1

You can do this using reduce if you don't need IE 8 support:

var newItem = item.reduce(function (o, c) {
    o[c.id] = c.quantity;
    return o;
}, {}); 
Andy E
  • 338,112
  • 86
  • 474
  • 445