Tom
Tom

Reputation: 1457

Is there a way to specify the order of the result of Object.values()

I get an item from an API in the following shape :

data : {
    "56": { ... }, //item1
    "57": { ... }, //item2
    "58": { ... }, //item3
}

And I want an array of Object looking like this :

[
    { ... }, //item1 with key "56"
    { ... }, //item2 with key "57"
    { ... }  //item3 with key "58"
]

This can of course be obtained with Object.values(data) . But since Javascript does not guarantee the order of an object's properties, I would like to find a way to use the properties' keys to sort the result and guarantee the order of the array of object I will get. Is this doable ?

Edit : as suggested in the comments, I could use Object.keys(), sort the result and then use it to build my array, but I am wondering if there is a more direct and elegant way to achieve this.

Upvotes: 1

Views: 55

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386710

You could get the entries, sort them and map only the values.

data = Object
    .entries(object.data)
    .sort(([a], [b]) => a - b)
    .map(([, v]) => v)

Upvotes: 5

Related Questions