0

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.

Tyler Bean
  • 417
  • 1
  • 4
  • 14
  • 2
    There are no sorted objects – Jonas Wilms May 28 '19 at 10:29
  • You use an array for sorted list, but then you dont have specific keys then. You can use an object for a named list, but that is not a garanteed ordered list. – Martijn May 28 '19 at 10:31
  • so have you tried to sort the array and assign keys from sorted array? Perhaps those will be sorted in this case. However, like the answer in https://stackoverflow.com/q/29623333/3995261 suggests, it's hardly a good idea to rely on the keys being sorted – YakovL May 28 '19 at 13:31
  • @JonasWilms ES6 guarantees key insertion order remains so you actually can use object keys for sorting in ES6, ES5 did not guarantee object key order. – Adrian Brand May 28 '19 at 21:49

2 Answers2

0

You can use Object.fromEntries to create such an object. But one thing to note here is that Object does not have sorted keys.

var data = [
  {
    "name": "Name VIC",
    "state": "Victoria"
  },
  {
    "name": "Name NSW",
    "state": "New South Wales"
  }
];

var newData = Object.fromEntries(data.map(el => [el.state, el]));

console.log(newData);
void
  • 36,090
  • 8
  • 62
  • 107
0

const array = [
  {
    "name": "Name VIC",
    "state": "Victoria"
  },
  {
    "name": "Name NSW",
    "state": "New South Wales"
  }
];

const states = array => array.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).reduce((result, state) =>  { result[state.state] = state; return result; }, {});

console.log(states(array))
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60