I have a typescript file & an array of objects and the keys are in sorted manner. But i wants the order of keys in a specific manner. The object is coming from the database and keys inside every object are in sorted manner.
Asked
Active
Viewed 49 times
-1
-
for example original array is something like which is coming from database Array = [ { class = "", date = "", id = "", level = "", name = "", parent = "", value = "", unique = "" }, { class = "", date = "", id = "", level = "", name = "", parent = "", value = "", unique = "" }, and so on ] and the expected array should be array = [ { date = "", class = "", name = "", parent = "", value = "", id = "", unique = "" }, and so on ] – Vishal Jun 29 '22 at 09:02
-
Properties in JavaScript are *mostly* in insertion order, see [details here](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order). You need to tweak whatever creates those objects to make sure they are created as you wish. – Joachim Sauer Jun 29 '22 at 09:12
-
But the data is coming from the database. in key sorted manner. – Vishal Jun 29 '22 at 09:19
-
*How* is it coming from the DB? What turns it into JS objects? Some code has to be responsible for that. Check what that code does. You can't send "JavaScript objects" over network connections, they have to be serialized in *some way* (often JSON). And then *something* needs to take that serialized form and turn it into JS objects. – Joachim Sauer Jun 29 '22 at 09:23
1 Answers
0
You can just remap it to another array and change the order of the keys
Assuming you have an array of objects dbResults
coming from the database and the initial order of keys is: class, date, id, level, name, parent, value, unique
dbResultsRemapped = dbResults.map((row) => ({
date: row.date,
class: row.class,
name: row.name,
parent: row.parent,
value: row.value,
id: row.id,
unique: row.unique,
level: row.level,
}))
The remap above will change the order of the keys to: date, class, name, parent, value, id, unique, level

chosen
- 23
- 5