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' }
}
5
  • Use array.reduce and code it yourself? Commented Oct 14, 2016 at 15:27
  • New Set(array) <- that would create an array-like object, a Set Commented Oct 14, 2016 at 15:27
  • @user2415266 maybe you could help him out since it seems he's new to programming Commented Oct 14, 2016 at 15:36
  • @Wade maybe he could search before asking a duplicate question Commented Oct 14, 2016 at 15:36
  • 3
    @user2415266 maybe you should read the ideologies stack overflow is trying to represent before being so rude to new contributors and programmers Commented Oct 14, 2016 at 15:45

3 Answers 3

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)

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

Comments

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)

1 Comment

Nice solution! You should check out @adeneo 's answer using Array.reduce, it does the same thing but using javascript's built in methods
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.