Reputation: 129
I know dealing with Objects in Javascript is difficult to predict the order of items, but is there a way to organise days of the week in order, and not so they are alphabetical in React or vanilla JS...
I want to know if it's possible to take a given React Object model like this:
this.state = {
days: {
friday: {
temperature: 34
},
monday: {
temperature: 28
},
tuesday: {
temperature: 29
}
}
}
To return in day order, like this:
this.state = {
days: {
monday: {
temperature: 28
},
tuesday: {
temperature: 29
},
friday: {
temperature: 34
}
}
}
I am intrigued as I am having a tough time to believe there's not an out of the box way, without using Arrays etc.
Many thanks for your opinion / help on this :)
Upvotes: 1
Views: 96
Reputation: 3302
You could solve it using Array.prototype.sort
method. First sort the days and then use Array.prototype.reduce
method to make your required object.
const data = {
days: {
friday: {
temperature: 34,
},
monday: {
temperature: 28,
},
tuesday: {
temperature: 29,
},
},
};
const days = {
sunday: 1,
monday: 2,
tuesday: 3,
wednesday: 4,
thursday: 5,
friday: 6,
saturday: 7,
};
const ret = Object.keys(data.days)
.sort((x, y) => days[x] - days[y])
.reduce(
(prev, c) => {
const p = prev;
p.days = { ...p.days, [c]: data.days[c] };
return p;
},
{ days: {} }
);
console.log(ret);
Upvotes: 2
Reputation: 2486
let mystate = {
days : [
{
day: 'friday',
temperature: 34
},
{
day: 'monday',
temperature: 28
},
{
day:'tuesday',
temperature: 29
}
]
};
console.log(mystate.days.sort((a,b)=>a.temperature-b.temperature))
Upvotes: 1
Reputation: 6264
Non numeric properties are enumerated in the order in which they are created
So to "force" the order, you could do something like:
var x = {
days: {
sunday: 7,
monday: 1,
tuesday: 2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6
}
};
const getValues = (o, k) => k.reduce((a, n) => ({ ...a,
[n]: o[n]
}), {});
console.log(x.days);
x.days = getValues(x.days, ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']);
console.log(x.days);
However, it's probably never a good idea to depend on the order of keys in an object - refactor the code that accesses the object to access the keys in the defined order you want
var x = {
days: {
sunday: 7,
monday: 1,
tuesday: 2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6
}
};
['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
.forEach(k =>
console.log(k, x.days[k])
);
Upvotes: 2