-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
  • 274,082
  • 63
  • 437
  • 513
CurlyFro
  • 1,862
  • 4
  • 22
  • 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
  • 223,194
  • 41
  • 299
  • 337