I have a javascript object in a firebase realtime database that has a structure similar to the following:
const obj = {
"quotes" : {
"Anon" : {
"-MZN5R9TUU5eLneHz2F_" : {
"quote" : "I am a quote",
"timestamp" : "1619616711347",
"htmlId" : "id517321"
}
},
"Secret Quoter" : {
"-D9NF75TGVSeJLABz1W_" : {
"quote" : "I am another quote",
"timestamp" : "1690016711317",
"htmlId" : "id519912"
},
"-DZNfR5THESeJLeHz1F_" : {
"quote" : "I am a different quote",
"timestamp" : "1349616899347",
"htmlId" : "id515618"
}
},
"General Kenobi" : {
"-MZR666TUUGeLneHzHF_" : {
"quote" : "Hello There",
"timestamp" : "1919616711347",
"htmlId" : "id511321"
}
}
}
};
Now I want to reorder the object entries based on the highest timestamp
attribute of each object (assuming the embedded object of each author of the quote is correctly sorted by timestamp), so the parsed response in this case would be:
{
"quotes" : {
"General Kenobi" : {
"-MZR666TUUGeLneHzHF_" : {
"quote" : "Hello There",
"timestamp" : "1919616711347",
"htmlId" : "id511321"
}
},
"Secret Quoter" : {
"-D9NF75TGVSeJLABz1W_" : {
"quote" : "I am another quote",
"timestamp" : "1690016711317",
"htmlId" : "id519912"
},
"-DZNfR5THESeJLeHz1F_" : {
"quote" : "I am a different quote",
"timestamp" : "1349616899347",
"htmlId" : "id515618"
}
},
"Anon" : {
"-MZN5R9TUU5eLneHz2F_" : {
"quote" : "I am a quote",
"timestamp" : "1619616711347",
"htmlId" : "id517321"
}
}
}
};
How would I go about doing this? There appears to be a lot of advice for sorting an array of objects, but none for actually sorting a singular object's entities by it's embedded values.
EDIT: Thanks for all the answers. To summarise, I have avoided this issue entirely by redesigning my DB schema so that quotes
is an array of objects, each with a author
attr. E.g.
{
"quotes" : [
{
"author" : "General Kenobi",
"quote" : "Hello There",
"timestamp" : "1919616711347",
"htmlId" : "id511321"
},
// More quotes here...
]
It's then possible to use the traditional method of sort() to order the list by the highest timestamp downwards. For the sake of having the question answered, I'll still accept one of the suggestions but I would recommend readers to consider if the structure of their object is correct before trying to order their object as it's a lot easier to do so with an array.