Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript create array of Object property values

Given this Object in Javascript

{
  "0": "hello",
  "1": { text: "world" }
}

What's the shortest way to create this array from that object?

[
  "hello",
  { text: "world" }
]

I've seen somebody using Array.prototype.splice(theObject) but it doesn't seem to work for me.

Update:

  1. Order of output needs to be guaranteed
  2. 0 and 1 can be any arbitrary string value and the order at property level needs to be maintained in the corresponding array.
  3. Needs to work with Node.js 6
like image 217
Alexander Zeitler Avatar asked Mar 06 '23 15:03

Alexander Zeitler


2 Answers

Just use Object.values:

console.log(Object.values({
  "0": "hello",
  "1": { text: "world" }
}));
like image 188
Faly Avatar answered Mar 09 '23 06:03

Faly


If you want to be sure that the original keys of the object correspond to the positions in the resulting array, you can't rely on Object.values() or a for ... in loop. You can use Object.keys() and sort that array.

var keys = Object.keys(yourObject);
keys.sort();
var array = keys.map(key => yourObject[key]);

Now understand that the call to .sort() can include a comparator function to impose any ordering desired on the original object keys. The sample in the OP is very simple, and the above would work. However more complicated keys might require a custom comparator.

like image 22
Pointy Avatar answered Mar 09 '23 06:03

Pointy