Closed geron closed 8 years ago
What would be the sorting function? Right now it's using whatever property order you have which is desired in most case. #22 was also about sorting keys so I see some users do want sorting their keys but JSONFormatter should not be in that business. All of modern JavaScript VMs respect your property orders as you create so it's easy to resort your object properties with a simple loop.
let obj = {one: 1, three: 3, two: 2}
let newObj = {};
Object.keys(obj).map(k => [k, obj[k]]).sort((a, b) => a[1] - b[1]).forEach(pair => newObj[pair[0]] = pair[1])
Something like that. BTW I wrote that JS code on the fly. Don't expect it to actually work
I ended up implementing:
import isPlainObject from 'is-plain-object';
function sortSchema(schema) {
if (!isPlainObject(schema)) {
return schema;
}
const sortedSchema = {};
Object.entries(schema).sort((a, b) => {
if (a[0] < b[0]) {
return -1;
}
else if (a[0] > b[0]) {
return 1;
}
else {
return 0;
}
}).forEach(pair => {
sortedSchema[pair[0]] = sortSchema(pair[1]);
});
return sortedSchema;
}
But I really think this should be part of this library. Especially because there are edge cases: like it would be great if required
field would also be sorted by name, but then one has to parse JSON schema to know where those fields are.
This seems pretty easy to do by adding a
.sort()
call inscope.getKeys
. Would you accept a patch for this?