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:
0
and 1
can be any arbitrary string value and the order at property level needs to be maintained in the corresponding array. Just use Object.values:
console.log(Object.values({
"0": "hello",
"1": { text: "world" }
}));
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.
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