Converting Object to Array using ES6 features
I like the old school way:
var i=0, arr=[];
for (var ob in inputObj)
arr[i++]=ob;
Old school wins the jsperf test by a large margin, if not the upvotes. Sometimes new additions are "mis-features."
just use Object.values
Object.values(inputObj); // => ['foo', [1,2,3], null, 55]
Update August 2020
As a summary, in ES6, there are three (3) variations to convert an Object to an Array as follows:
const MyObjects = { key1: 'value 1', key2: 'value 2', };
// Method 1: Converts the keys to Array
// --------------------------------------
Object.keys(MyObjects);
// ['key1', 'key2']
// Method 2 Converts the Values to Array
// --------------------------------------
Object.values(MyObjects);
// ['value 1', 'value 2']
// Method 3 Converts both Values and Keys
// --------------------------------------
Object.entries(MyObjects);
// [ ['key1', 'value 1'], ['key2', 'value 2'] ]
Converting an Array back to an Object can be done as follows:
const array = [ ['one', 1], ['two', 2], ];
Object.fromEntries(array);
// { one: 1, two: 2 }
Use (ES5) Array::map
over the keys
with an arrow function (for short syntax only, not functionality):
let arr = Object.keys(obj).map((k) => obj[k])
True ES6 style would be to write a generator, and convert that iterable into an array:
function* values(obj) {
for (let prop of Object.keys(obj)) // own properties, you might use
// for (let prop in obj)
yield obj[prop];
}
let arr = Array.from(values(obj));
Regrettably, no object iterator has made it into the ES6 natives.