If you're converting an array-like object to an array you can use:
var array = Array.prototype.slice.call(arrayLike) // returns an array
Note that unlike Array.prototype.slice.call(), Array.from() is slow and always returns a dense array even if the given array-like is sparse. (In V8 it is a packed array.)
But since the question is how to cast a plain JavaScript object to an array, the answer is there is no built-in way other than to copy all own key/value pairs from the source object to a new array:
function cast2Array(value) {
if (Array.isArray(value)) {
return value;// value is already an array
}
if (value===null || value===undefined) {
return [];// value is nullish
}
if (typeof value=="function" || Object(value)!==value) {
return [value];// value is either a function or a primitive
}
// value is an object. Get property descriptors to apply to array
var length, descriptors = Object.getOwnPropertyDescriptors(value);
delete descriptors.length;// avoid potential RangeError
try {
length = Number(value.length);// throws if can't cast to number
}
catch(e) {
}
// Return new array with integer length >= 0 and descriptors applied
return Object.defineProperties(Array(length > 0? length-length%1: 0), descriptors);
}
// Converts array-like objects to arrays
cast2Array(new String('test'));// ['t', 'e', 's', 't']
// Note: Unlike other methods the object doesn't need a length property
cast2Array({0:'a', 1:'b', 2:'c'});// ['a', 'b', 'c']
// or if value is already an array, no new array is created
cast2Array(value);// returns `value`
// Casting primitives simply returns an array containing the primitive
cast2Array('test');// ['test']
// or an empty array if the cast value is nullish
cast2Array(null);// []
If what you want is to cast a plain object to an iterable for use with modern features like for...of and the spread operator, use Object.entries() which takes a plain object and returns an array containing all of its own enumerable key/value pairs.
var object = {a:1, b:2, c:3};
Object.entries(object)// returns [['a', 1], ['b', 2], ['c', 3]]
objectfromtypeoffor arrays. Arrays are just objects with numeric properties, a few extra methods, and a magiclengthproperty.obj = {}beforeobj = arr.typeofimplied modern code can use developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…