Three quick ways to convert objects to arrays

Easily convert objects to arrays and iterate to your heart’s content.

There are multiple ways of converting an object to an array (which, also is an object but a different one at that.)

Method 1: A simple Object.values() method

The first idea that comes to mind is to just use Object.keys(), Object.values() or Object.entries() to generate an array.

const numO = { a: 1, b: 2, c: 3, d: 4, e: 5 };

console.log(Object.values(numO));
// [ 1, 2, 3, 4, 5 ]

Method 2: Apply transformation logic during object to array conversion

If you are going fancy about the conversion and want to include some logic therein -

const numO = { a: 1, b: 2, c: 3, d: 4, e: 5 };

const arr = [];

Object.values(numO).forEach(val => arr.push("a" + val));
console.log("arr: ", arr);
// [ 'a1', 'a2', 'a3', 'a4', 'a5' ]

Method 3: Use slice and call

Remember that call of one object can be used against another object? We can use this principle to call an array function against the array-like object.

getSum(1, 2, 3, 4, 5);
function getSum() {
  const arr = Array.prototype.slice.call(arguments);

  console.log(arguments);
  // { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }

  console.log("arr: ", arr);
  // arr:  [ 1, 2, 3, 4, 5 ]
}

Method 3.1: Use Array.from()

Array.from() works for array-like iterables including objects. So, we could use them for objects that are arrays in their hearts. This works similar to the previous method in principle and therefore does not deserve a “method” by its own.

getSum(1, 2, 3, 4, 5);
function getSum() {
  const arr = Array.from(arguments);

  console.log(arguments);
  // { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }

  console.log("arr: ", arr);
  // arr:  [ 1, 2, 3, 4, 5 ]
}

Conclusion

I prefer Object.values() (or keys/entries ) to subject an object to array-like operations (yes, I get the subject/object philosophical implications).

Array.prototype.slice() may be the best performer of the lot.

comments powered by Disqus