Is there a way to sort/order keys in JavaScript objects?
Not within the object itself: the property collection of an object is unordered.
One thing you could do is use Object.keys()
, and sort the Array, then iterate it.
Object.keys(data)
.sort()
.forEach(function(v, i) {
console.log(v, data[v]);
});
Patches (implementations) for browsers that do not support ECMAScript 5th edition:
Object.keys
Array.forEach
Sorting object property by values
Move them to an array, sort that array, and then use that array for your purposes. Here's a solution:
let maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
let sortable = [];
for (var vehicle in maxSpeed) {
sortable.push([vehicle, maxSpeed[vehicle]]);
}
sortable.sort(function(a, b) {
return a[1] - b[1];
});
// [["bike", 60], ["motorbike", 200], ["car", 300],
// ["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]
Once you have the array, you could rebuild the object from the array in the order you like, thus achieving exactly what you set out to do. That would work in all the browsers I know of, but it would be dependent on an implementation quirk, and could break at any time. You should never make assumptions about the order of elements in a JavaScript object.
let objSorted = {}
sortable.forEach(function(item){
objSorted[item[0]]=item[1]
})
In ES8, you can use Object.entries()
to convert the object into an array:
const maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
const sortable = Object.entries(maxSpeed)
.sort(([,a],[,b]) => a-b)
.reduce((r, [k, v]) => ({ ...r, [k]: v }), {});
console.log(sortable);
Sort object keys/entries in specific order
You almost had it, the only issue is that you're not checking if sortOrder
actually contains the key you're iterating or not.
If you do sortOrder.indexOf(x)
but x
is not in sortOrder
, then indexOf
will return -1, explaining why the non-existent keys are always on top (--1 === +1). See reference for more info.
The fix is to manually put all keys that are not present in sortOrder
at the end of the array:
if (!sortOrder.includes(a)) return 1
if (!sortOrder.includes(b)) return -1
So in the end, you'd have this:
const ordered = Object.keys(data).sort((a, b) => {
if (!sortOrder.includes(a)) return 1
if (!sortOrder.includes(b)) return -1
return sortOrder.indexOf(a) - sortOrder.indexOf(b);
});
How to sort array of objects in Javascript by their keys in order?
As @ggorlen suggested, the order of keys in an object is not guaranteed. You could iterate over orderedData
to access the keys from each object in the order you need:
jData.map((item) => (
<ul>
orderedData.map((key) => <li>{key}: {item[key]}</li>)
</ul>
));
Custom sort/order object array based on keys stored in a string array js
Based upon your description, the approach below pulls out the column names that are not in the column_order
, and concatenates those to the column_order
array. This provides an array of column names in the correct order.
Then, the task becomes looping over the actual applicants
data and the sortedColumns
in order to reconstruct the applicants
in the newOrder
.
// Given:
const applicants = [{applicant_id: 5, recruiter_id: null, resume_cv_id: "null", cover_letter_id: "null", nda_id: null},
{applicant_id: 6, recruiter_id: null, resume_cv_id: "null", cover_letter_id: "null", nda_id: null}];
const column_order = ['applicant_id', 'resume_cv_id'];
// Sort Columns
const sortedColumns = column_order.concat(
Object.keys(applicants[0])
.filter(k => k !== column_order[0] && k !== column_order[1])
);
// Create new applicants in correct column order
const newOrder = applicants.map(a => {
let row = {};
sortedColumns.forEach(c => row[c] = a[c]);
return row;
});
console.log(newOrder);
Javascript sort object by key within nested objects
Anotner one sorting approach
const obj = {4:{1:[{order:1,name:'Test 4'}]},0:{15:[{order:7,name:'Test 1'},{order:3,name:'Test 3'},],12:[{order:1,name:'Test 2'}]}};
const result = Object.entries(obj).flatMap(([u1, v1]) =>
Object.entries(v1).flatMap(([u2, v2]) =>
v2.map((v3) => ({ key: u1*1_000 + u2 + v3.order/1_000, item: v3 }))
)
)
.sort(({ key: a }, { key: b }) => a - b)
.map(({ item }) => item);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }
sort objects by key value 0 by number size
ES6 states a traversal order for object keys (see this article):
- Integer indices in ascending numeric order.
- Then, all other string keys, in the order in which they were added to the object.
- Lastly, all symbol keys, in the order in which they were added to the object.
This means that as long as you're using non integer keys of strings or symbols (not both), you can "sort" an object keys by creating a new object with the keys in the insertion order you need.
For example, use Object.entries()
to get an array of [key, value]
pairs, sort by user_id
, and then convert back to an object using Object.fromEntries()
:
const obj = { key_1: { user_id: 3 }, key_2: { user_id: 1 }, key_3: { user_id: 2 }}
const result = Object.fromEntries(
Object.entries(obj)
.sort(([, a], [, b]) => a.user_id - b.user_id)
)
console.log(result)
Related Topics
Converting 24 Hour Time to 12 Hour Time W/ Am & Pm Using JavaScript
Share Variables Between Files in Node.Js
JavaScript || or Operator with an Undefined Variable
How to Persist a Es6 Map in Localstorage (Or Elsewhere)
Find All Text Nodes in HTML Page
Why Isn't [1,2,3] Equal to Itself in JavaScript
Es6 Class Multiple Inheritance
Jquery Drop Down Menu Closing by Clicking Outside
How to Create a Session Using JavaScript
Jquery: How to Get the Event Object in an Event Handler Function Without Passing It as an Argument
Tried to Load Angular More Than Once
Understanding JavaScript Scope with "Var That = This"
Fade in on Scroll Down, Fade Out on Scroll Up - Based on Element Position in Window
Sort an Array with Arrays in It by String
!Function(){ }() VS (Function(){ })()
Input File to Array JavaScript/Jquery