Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn an object with keys as indexes into an array in JavaScript? [duplicate]

Tags:

javascript

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()?

like image 566
Nilam Avatar asked Apr 30 '16 18:04

Nilam


People also ask

Can we convert object to array in JavaScript?

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.

How do you turn an object into an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .

Can JavaScript object have duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

Can object keys be arrays?

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.


1 Answers

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.

like image 131
Oriol Avatar answered Sep 22 '22 04:09

Oriol