1

I have this data below with I want to push into an array but ordering it by name(x)

Here is the data:

params:
  name2:
    height: 2
  name0:
    height: 0
  name1:
    height: 3

And here is the code:

 data.f = []

  Object.keys(data.params).forEach((key, idx) => {
      data.f.push({
          ...data.params[key],
          name: `${idx} - ${key}`
      });
  })

At the moment it's just pushing it into the array as it reads it but it's not ordered.

How can I order it either whiles it's read or after it's been populated?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Possible duplicate of [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – Jozef Cipa Oct 17 '18 at 11:16
  • 1
    Please provide a [mcve] using the `[<>]` snippet editor you get when you [edit](https://stackoverflow.com/posts/52853471/edit) – mplungjan Oct 17 '18 at 11:17
  • Don't use enumerated properties. It's cumbersome to work with them. Better use a single property containsing an Array. – Thomas Oct 17 '18 at 11:23

2 Answers2

0

You can do it afterwards using the sort function with your custom compareFunction

data.f.sort((a,b) => a.name > b.name)

Moreover, if I may suggest, you don't need to create an array and push into it. you can just use map function and write:

data.f = Object.keys(data.params).map((key, idx) => {
  return {
      ...data.params[key],
      name: `${idx} - ${key}`
  };
});
  • The sort at the moment is giving me is wrong... I need name: to display as lowest idx with name0 (lowest name number) for example: name: 0 - name0, 1 - name1 etc –  Oct 17 '18 at 11:49
  • could you please share some demo data. maybe part of your `data.f` array before sorting – Sajal Preet Singh Oct 17 '18 at 11:51
0
Object.keys(data.params)
.sort((a,b) => data.params[a].height > data.params[b].height)
.forEach((key, idx) => {
      data.f.push({
          ...data.params[key],
          name: `${idx} - ${key}`
      });
  })