I have a json object like below. I have also searched the previously posted questions
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