1

I have an array, say [{ id: 'first' }, { id: 'second' }]

Are there any native methods I'm missing that will convert the array into an array-like object? I've seen plenty of answers asking about the other direction, and recommending Array.prototype.slice.call (or the newer Array.from), but I can't find anyone asking about this. For the above example, I'd want to get the following output:

{
  0: { id: 'first' }
  1: { id: 'second' }
}
Aurora0001
  • 12,155
  • 5
  • 48
  • 51

3 Answers3

4

Reducing it

var array = [{ id: 'first' }, { id: 'second' }];
var obj   = array.reduce( (a,b,i) =>  {return a[i]=b,a},{})

console.log(obj)

Check out the documentation on Array.reduce on MDN (Mozilla Developer Network)

Jay
  • 981
  • 1
  • 11
  • 20
adeneo
  • 303,455
  • 27
  • 380
  • 377
1

You could just iterate through the array and add the values to the respective index

var arr = [{ id: 'first' }, { id: 'second' }];
var set = {};
arr.forEach(function(value, index){
    set[index] = value; 
})

console.log(set)
taguenizy
  • 2,020
  • 1
  • 7
  • 25
  • Nice solution! You should check out @adeneo 's answer using `Array.reduce`, it does the same thing but using javascript's built in methods – Jay Oct 14 '16 at 15:38
0

Not a native method, but the following helper function should do the trick:

var arr = [{ id: 'first' }, { id: 'second' }];

function toArrayLike(arrayToConvert) {
    var retVal = {};
    Object.keys(arrayToConvert).forEach(function(key) {
        retVal[key] = arrayToConvert[key];
    });
    return retVal
}

var arrayLike = toArrayLike(arr);
console.log(arrayLike);