I have an object in JS structured as follows:
[{
"x": 2.31,
"y": 0.538
},
{
"x": 7.07,
"y": 0.469
},
{
"x": 6.02,
"y": 0.469
},
{
"x": 2.18,
"y": 0.458
}]
I need to sort by one of the keys in each element (sort by x). The result would look like this:
[{
"x": 2.18,
"y": 0.458
},
{
"x": 2.31,
"y": 0.538
},
{
"x": 6.02,
"y": 0.469
},
{
"x": 7.07,
"y": 0.469
}]
The following approach doesn't work with the above structure:
var sorted = [];
for(var key in dict) {
sorted[sorted.length] = key;
}
sorted.sort();
Nor does the following:
function sortObject(o) {
return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}