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 ^_^

6
  • 1
    That is not JSON (which is a serialization format). That is simply a javascript array of objects. Commented Jun 29, 2015 at 14:37
  • 1
    Objects have string keys, not numeric keys. Commented Jun 29, 2015 at 14:37
  • "but errors"?? You should share your experience of these errors. Commented Jun 29, 2015 at 14:38
  • You're replacing new_item on every single iteration of your loop. Commented Jun 29, 2015 at 14:40
  • Take a look at this question, stackoverflow.com/questions/920930/… Commented Jun 29, 2015 at 14:43

3 Answers 3

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.

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

Comments

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

Comments

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;
}, {}); 

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.