I'm trying to sort, by a single value, a collection of objects that themselves have objects for their values.
To be clear, I want to sort my results by the name string in each object's value object.
This is different from other questions (I believe... including the one that is listed above as "Possible duplicate...") in that I am sorting from a value that consists of an object of other values, not simply from a single value.
I have an object that looks like:
foo = {
9876: {name: 'Banana', id:'875465'},
4536: {name: 'Pear', id:'285610'},
8732: {name: 'Apple', id:'013452'}
}
I want to sort that object, alphabetically, by the name value.
If I try to sort by Object.values
the returned results are correctly sorted by the name value but thr return looks like:
[
0: {name: 'Apple', id:'013452'}
1: {name: 'Banana', id:'875465'}
2: {name: 'Pear', id:'285610'}
]
What I need, however, is to retain my same collection of objects, just sorted properly. No array, no numeric keys... I just want foo
as it was above, but sorted by name like:
foo = {
8732: {name: 'Apple', id:'013452'},
9876: {name: 'Banana', id:'875465'},
4536: {name: 'Pear', id:'285610'}
}
How do I do that in Javascript?
For completeness, here is the sorting method I am currently attempting to use:
const sortStuff = (key) => {
return (a, b) => {
if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
return 0;
}
const avalue = (typeof a[key] === 'string') ?
a[key].toLowerCase() : a[key];
const bvalue = (typeof b[key] === 'string') ?
b[key].toLowerCase() : b[key];
let comp = 0;
if (avalue > bvalue) {
comp = 1;
}
if (avalue < bvalue) {
comp = -1;
}
return comp
}
}
and I consume that like:
Object.values(foo).sort(sortStuff('name'))