I want to convert an object with indexes as keys, into an array in JavaScript.
For example:
Input: obj ={1: 'banana', 2: 'apple',3:'orange' }
Output: ['orange','apple','banana' ]
I have tried with 'Array.prototype.reverse.apply(obj)', but not able to get the result.
var obj ={1: 'banana', 2: 'apple',3:'orange' };
var res =Array.prototype.reverse.apply(obj);
console.log(res); // return the same object, not reverse
What are the other usages of Array.prototype.reverse()?
JavaScript Objects Convert object's values to array You can convert its values to an array by doing: var array = Object. keys(obj) . map(function(key) { return obj[key]; }); console.
To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
Description. Object. keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object . The ordering of the properties is the same as that given by looping over the properties of the object manually.
You can first convert your almost-array-like object to a real array, and then use .reverse()
:
Object.assign([], {1:'banana', 2:'apple', 3:'orange'}).reverse();
// [ "orange", "apple", "banana", <1 empty slot> ]
The empty slot at the end if cause because your first index is 1
instead of 0
. You can remove the empty slot with .length--
or .pop()
.
Alternatively, if you want to borrow .reverse
and call it on the same object, it must be a fully-array-like object. That is, it needs a length
property:
Array.prototype.reverse.call({1:'banana', 2:'apple', 3:'orange', length:4});
// {0:"orange", 1:"apple", 3:"banana", length:4}
Note it will return the same fully-array-like object object, so it won't be a real array. You can then use delete
to remove the length
property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With