Javascript Sort An Object By Keys Based On Another Array?
Solution 1:
The JavaScript specification does not require that object keys maintain their order, so it is not safe to attempt to sort them. It is up to each environment to implement the standard, and each browser does this differently. I believe most modern browsers will sort keys on a first-in-first-out basis, but since it is not part of the standard, it is not safe to trust this in production code. It may also break in older browsers. Your best bet is to place your object keys into an array, sort that array and then access the values of the object by the sorted keys.
varmyObject= { d:3, b:1, a:0, c:2 },sortedKeys=Object.getOwnPropertyNames(myObject).sort();
You could then map the ordered values into a new array if you need that.
var orderedValues = sortedKeys.map(function (key) { return myObject[key]; });
Solution 2:
As QED2000 pointed out, even if you create a new object, there's no guaranty that the properties will remain in a specific order. However you can sort the keys depending on a different array.
<script>functionsortArrayByArray(a, b)
{
return order.indexOf(a) - order.indexOf(b);
}
var order = newArray('name', 'dob', 'address');
var customer = newArray();
customer['address'] = '123 fake st';
customer['name'] = 'Tim';
customer['dob'] = '12/08/1986';
customer['dontSortMe'] = 'this value doesnt need to be sorted';
var orderedKeys = Object.keys(customer).sort(sortArrayByArray);
orderedKeys.forEach(function (key) {
document.write(key + "=" + customer[key] + "<br/>");
});
</script>
The output is
dontSortMe=this value doesnt need to be sorted
name=Tim
dob=12/08/1986address=123 fake st
Post a Comment for "Javascript Sort An Object By Keys Based On Another Array?"