I have an array like this:
[
{
"name": "Name VIC",
"state": "Victoria"
},
{
"name": "Name NSW",
"state": "New South Wales"
}
]
I need to create an object from the array, with the state
as a key, and sorted.
{
"New South Wales": [
{
"name": "Name NSW",
"state": "New South Wales"
}
],
"Victoria": [
{
"name": "Name VIC",
"state": "Victoria"
}
],
}
Notice that the NSW
state has to be first in the object, but it is not the first item in the array. So after using loop through the array to create an object, the result is that the Victoria
state appears first. I know that I can sort the result object, with many more codes. But is there any ways to create an object, whereas the keys are sorted immediately? (please check my code below)
function () {
let result = {}
array.forEach((item) => {
if (!result[item.state]) {
result[item.state] = []
}
result[item.state].push(item)
})
return result
}
Update Please read my question again. I know that there are a lot of ways for sorting the keys, but it's not what I meant. I want the keys to be sorted right in the loop, not after the object is created.