I am facing an issue where I am getting Api results which I can't modify for my convenience and I have to deal with what I got. I get an object filled with arrays which also have objects inside them similar to this one:
{
sectionOne: [{game: 1, order: 3},{game: 2},{game: 3},{game: 4}],
sectionTwo: [{game: 1, order: 1},{game: 2},{game: 3},{game: 4}],
sectionThree: [{game: 1, order: 2},{game: 2},{game: 3},{game: 4}],
}
In all sections the first element in the array always has a key called order, which is the position the array needs to be in the object. From the top example, the expected results should be:
{
sectionThree: [{game: 1, order 1},{game: 2},{game: 3},{game: 4}],
sectionOne: [{game: 1, order 2},{game: 2},{game: 3},{game: 4}],
sectionTwo: [{game: 1, order 3},{game: 2},{game: 3},{game: 4}],
}
PS. I know there isn't a method that can sort objects, I tried mapping them with entries, with keys but I don't know how to go deeper into the structure and target them.
CodePudding user response:
Does this work for you?
arr = arr.sort((a, b) => a[0].order - b[0].order)
CodePudding user response:
If I understood right you need function like:
const sortKeys = (obj) => {
return Object.keys(obj).sort().reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {});}