0

I have a json object like below. I have also searched the previously posted questions

Sort JavaScript object by key

Sorting a JavaScript object by property name

can I prevent automatic sort of JS Object numeric property?


let sampleJson = {  
    "4":[{"id":5,"quantity":4,"units":"kg"}],
    "3":[{"id":4,"quantity":3,"units":"kg"}],                  
    "4.5":[{"id":2,"quantity":4.5,"units":"kg"}],
    "5":[{"id":1,"quantity":5,"units":"kg"},    
         {"id":3,"quantity":5,"units":"kg"}]
}

let result = Object.keys(sampleJson).sort().reduce((accumulator, currentValue) => {
  console.log('Current Key ==> '+currentValue)
  accumulator[currentValue] = sampleJson[currentValue];
  return accumulator;
}, {});

console.log('Output : '+JSON.stringify(result))
// But it returns the output as { "3":[{"id":4,"quantity":3,"units":"kg"}], "4":[{"id":5,"quantity":4,"units":"kg"}], "5":[{"id":1,"quantity":5,"units":"kg"}, {"id":3,"quantity":5,"units":"kg"}], "4.5":[{"id":2,"quantity":4.5,"units":"kg"}] } // Expected Output { "3":[{"id":4,"quantity":3,"units":"kg"}], "4":[{"id":5,"quantity":4,"units":"kg"}], "4.5":[{"id":2,"quantity":4.5,"units":"kg"}], "5":[{"id":1,"quantity":5,"units":"kg"}, {"id":3,"quantity":5,"units":"kg"}], }

You can able to see the console log which returns the current value as expected. But when the last object gets added in to accumulator then the result changes. I need to know what has happened after all the objects got added. If it was because of the automatic sort of JS numeric property then how to prevent that. Kindly correct me if i'm wrong

Jeeva
  • 1,550
  • 12
  • 15
  • 1
    Are you sorting alphabetically or numerically - first thing that comes to mind is string vs number. – mnewelski Jul 04 '20 at 08:25
  • 1
    What you are asking is not possible. As [this answer](https://stackoverflow.com/a/30919039) implies, "integer indices" are always before other keys, including float-like indices. E.g. `{'1.5':1, 2:1}` will automatically change the order. – str Jul 04 '20 at 08:25
  • @str, But if i used **"5.0":[{"id":1,"quantity":5,"units":"kg"},{"id":3,"quantity":5,"units":"kg"}]** instead of 5. It sorts as expected. – Jeeva Jul 04 '20 at 08:35
  • 1
    @Jeeva But if you add another element `6:null`, then it won't. As already said, "integer indices" are always before other keys, including float-like indices. `5.0` is float-like and *not* an integer key. – str Jul 04 '20 at 08:46
  • @matt, I got the above json on grouping it based on the quantity. It contains both integer and float strings as a key. So I just changed the key with the same type which is a float. By using that, i can able to achieve the expected output – Jeeva Jul 04 '20 at 08:56

0 Answers0