3

Suppose I have large object

var object = { a: 1, b: 2, c: 3, d:4, e:5, f:6, g:7, h:8, i:9, j:10 ...};
var array = [];

Output is [1,2,3,4,5,6,7,8,9,10...]

how I can map object to an array in es6 ? please help me.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
azmul hossain
  • 1,321
  • 2
  • 11
  • 15

4 Answers4

3

You could use the keys, order them and return the value in an array.

var object = { a: 1, b: 2, c: 3, d:4, e:5, f:6, g:7, h:8, i:9, j:10};
var array = Object.keys(object).sort().map(k => object[k]);

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

You can use Object.keys()

let arr = Object.keys(obj).map((k) => obj[k])
Thalaivar
  • 23,282
  • 5
  • 60
  • 71
1

Depending on which browsers you're wanting to support, you can achieve this using Object.values() which is part of ECMAScript 2017:

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop...

MDN's Documentation on Object.values()

var
  obj = { a: 1, b: 2, c: 3, d:4, e:5, f:6, g:7, h:8, i:9, j:10 },
  values = Object.values(obj)
;

console.log(values);
Community
  • 1
  • 1
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • The question was tagged with `ecmascript-6` and specifies `in es6` in the title... – trincot Oct 26 '16 at 10:11
  • @trincot I'm well aware; I tagged it. This is why I prefaced my answer by mentioning that this uses a method defined in ECMAScript 2017, in the event OP is able to utilise that as well. Your comment is somewhat moot seeing as the answer you've marked this as a duplicate of asks for a jQuery solution. – James Donnelly Oct 26 '16 at 10:16
  • The duplicate asks for *"Is there an better way to convert an object to an array or maybe a function?"* without mentioning jQuery as a *requirement*. I chose that duplicate, since the highest voted answer is a pure JS solution that can serve as answer to the OP's question. I think it is appropriate. – trincot Oct 26 '16 at 11:27
  • wow. interesting. – azmul hossain Oct 26 '16 at 12:46
0

Try this simple approach

var object = { a: 1, b: 2, c: 3, d:4, e:5, f:6, g:7, h:8, i:9, j:10};
var array = Object.keys( object ).map( function(key){ return object[key] } );
console.log(array);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94