-1

I hope I'm asking the right question.

I have an array like this:

var arr = [{item: 1}, {item: 2}, {item: 3}];

I need to convert it to an object collection that looks like this:

{item1: {item: 1}, item2:{item:2}, item3:{item:3}}

Is there an easy way to do this?

Oriol
  • 249,902
  • 55
  • 405
  • 483
CurlyFro
  • 1,866
  • 4
  • 21
  • 39

1 Answers1

0

Just loop over arr and add the objects to an object.

var arr = [{item: 1}, {item: 2}, {item: 3}];
var obj = {};

for(var i = 0, len = arr.length; i < len; i++){
    obj['item'+i] = arr[i];
}

I'd suggest leaving this structure as an array unless you have a reason to have it be an object.

gen_Eric
  • 214,658
  • 40
  • 293
  • 332