sort json object in javascript
First off, that's not JSON. It's a JavaScript object literal. JSON is a string representation of data, that just so happens to very closely resemble JavaScript syntax.
Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you need to use an array. This will require you to change your data structure.
One option might be to make your data look like this:
var json = [{
"name": "user1",
"id": 3
}, {
"name": "user2",
"id": 6
}, {
"name": "user3",
"id": 1
}];
Now you have an array of objects, and we can sort it.
json.sort(function(a, b){
return a.id - b.id;
});
The resulting array will look like:
[{
"name": "user3",
"id" : 1
}, {
"name": "user1",
"id" : 3
}, {
"name": "user2",
"id" : 6
}];
Sorting a JSON object in Javascript
function sortJsonArrayByProperty(objArray, prop, direction){
if (arguments.length<2) throw new Error("sortJsonArrayByProp requires 2 arguments");
var direct = arguments.length>2 ? arguments[2] : 1; //Default to ascending
if (objArray && objArray.constructor===Array){
var propPath = (prop.constructor===Array) ? prop : prop.split(".");
objArray.sort(function(a,b){
for (var p in propPath){
if (a[propPath[p]] && b[propPath[p]]){
a = a[propPath[p]];
b = b[propPath[p]];
}
}
// convert numeric strings to integers
a = a.match(/^\d+$/) ? +a : a;
b = b.match(/^\d+$/) ? +b : b;
return ( (a < b) ? -1*direct : ((a > b) ? 1*direct : 0) );
});
}
}
sortJsonArrayByProperty(results, 'attributes.OBJECTID');
sortJsonArrayByProperty(results, 'attributes.OBJECTID', -1);
UPDATED: DON'T MUTATE
function sortByProperty(objArray, prop, direction){
if (arguments.length<2) throw new Error("ARRAY, AND OBJECT PROPERTY MINIMUM ARGUMENTS, OPTIONAL DIRECTION");
if (!Array.isArray(objArray)) throw new Error("FIRST ARGUMENT NOT AN ARRAY");
const clone = objArray.slice(0);
const direct = arguments.length>2 ? arguments[2] : 1; //Default to ascending
const propPath = (prop.constructor===Array) ? prop : prop.split(".");
clone.sort(function(a,b){
for (let p in propPath){
if (a[propPath[p]] && b[propPath[p]]){
a = a[propPath[p]];
b = b[propPath[p]];
}
}
// convert numeric strings to integers
a = a.match(/^\d+$/) ? +a : a;
b = b.match(/^\d+$/) ? +b : b;
return ( (a < b) ? -1*direct : ((a > b) ? 1*direct : 0) );
});
return clone;
}
const resultsByObjectId = sortByProperty(results, 'attributes.OBJECTID');
const resultsByObjectIdDescending = sortByProperty(results, 'attributes.OBJECTID', -1);
Sorting JSON in JavaScript
Sort with string, instead of number comparison.
const json = [ { "toothNumber": "01", "name": "John" }, { "toothNumber": "18", "name": "John" }, { "toothNumber": "19", "name": "John" }, { "toothNumber": "17", "name": "John" }, { "toothNumber": "01,32", "name": "John" }, { "toothNumber": "25,32", "name": "John" }, { "toothNumber": "", "name": "John" }, { "toothNumber": "15", "name": "John" }];
json.sort(function(a, b){
return a.toothNumber > b.toothNumber ? 1 : (a.toothNumber === b.toothNumber ? 0 : -1 );
});
console.log(json);
Sorting JSON object based on value type [array or numeral or string]
You could sort
the entries
of the object based on whether the value is an array or not. Then use Object.fromEntries()
to create a new object from the sorted entries
const obj = { field1: "ONE", field2: "TWO", field3: ["THREE1", "THREE2", "THREE3"], field4: "FOUR", field5: ["FIVE1", "FIVE2", "FIVE3"]};
const sortedEntries = Object.entries(obj) .sort((a, b) => Array.isArray(a[1]) - Array.isArray(b[1])); const newObj = Object.fromEntries(sortedEntries)
console.log(newObj)
How can I sort a complex JSON object efficiently?
You can you Object.entries
in order to iterate thought all key-value
pairs and then use Array.prototype.reduce
for composing the new object. Like so:
const data = JSON.parse('{ "myJson": { "firstGroup": { "0": [ { "month": 1.0, "amount": 1.7791170955479318, "name": "dummy1", "nr": 3 }, { "month": 2.0, "amount": 324.0, "name": "dummy2", "nr": 1 }, { "month": 3.0, "amount": 32323.0, "name": "dummy3", "nr": 2 } ], "yearlyResults": { "0": [ { "month": 1.0, "amount": 100000, "name": "dummy1", "nr": 3 }, { "month": 2.0, "amount": 3000000, "name": "dummy2", "nr": 1 }, { "month": 3.0, "amount": 60000, "name": "dummy3", "nr": 2 } ] } } }, "success": true }');
const object = data.myJson;
const sortSubGroupByProperty = (subGroup, property) => {
return subGroup.sort((a, b) => {
if (a[property] > b[property]) {
return 1;
}
else if (a[property] < b[property]) {
return -1;
}
return 0;
});
}
const result = Object.entries(object).reduce((result, entry) => {
const [groupName, group] = entry;
result[groupName] = {
...group,
0: sortSubGroupByProperty(group[0], 'nr'),
yearlyResults: {
...group.yearlyResults,
0: sortSubGroupByProperty(group.yearlyResults[0], 'nr')
}
};
return result;
}, {});
console.log(result);
javascript - sort nested json object
You can sort this array by using javascript sort
function.
const data = {
"1": {
"category": "Year",
"value": "2028",
"title": "Current Year",
"description": "",
"orderby": "3"
},
"2": {
"category": "Year",
"value": "2038",
"title": "First Year",
"description": "",
"orderby": "4"
},
"3": {
"category": "Year",
"value": "2016",
"title": "Base Year",
"description": "",
"orderby": "1"
},
"4": {
"category": "Year",
"value": "2018",
"title": "Previous Year",
"description": "",
"orderby": "2"
}
}
Object.keys(data).sort((a, b) => data[a].orderby - data[b].orderby).map(f => data[f])
Sort a json data with respect to user input
The easiest way would be to go through the list of strings and make a new array full of the strings that start with the user input. Then we can sort the matches and append the array of none matching strings to this list.
var users = [{
name: 'Devgad Mango'
},
{
name: 'Mantra santra'
},
{
name: 'Prag Mango'
},
{
name: 'Pirate aam Mango'
}, {
name: 'Mango raw'
},
];
function search(input) {
const matches = [];
const remeinder = [];
users.forEach(user => {
user.name.startsWith(input) ?
matches.push(user) :
remeinder.push(user);
});
console.log(matches, remeinder)
// now we sort the matches
matches.sort((a, b) => {
const aa = a.name.toLowerCase();
const bb = b.name.toLowerCase();
if (aa < bb) {
return -1;
}
if (aa > bb) {
return 1;
}
return 0;
});
console.log(matches);
// now we want to push the remeinders to the end of the sorted array.
matches.push(...remeinder);
console.log(matches);
}
search('Man')
node.js - Sort JSON objects by a value
Since these are objects' properties, their order is usually unknown and not guaranteed. To sort them by some internal property, you would first have to change the Object into an Array, for example:
const json = JSON.parse(getJsonFile());
const jsonAsArray = Object.keys(json).map(function (key) {
return json[key];
})
.sort(function (itemA, itemB) {
return itemA.score < itemB.score;
});
For more, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Related Topics
How to Display PDF (Blob) on iOS Sent from My Angularjs App
Are There JavaScript or Ruby Versions of "HTML Tidy"
How to Disable Browser Developer Tools
Ruby Array to JavaScript Array
How to Geocode 20 Addresses Without Receiving an Over_Query_Limit Response
Can Jquery .Keypress() Detect More Than One Key at the Same Time
Ruby with Watir: Handling JavaScript Popup Window
Switch on Ranges of Integers in JavaScript
How to Control the Back Button Event in Jquery Mobile
How to Pause Setinterval() Functions
How to Prevent Closing Browser Window
Using Queryselectorall to Retrieve Direct Children
What Does (Function (X,Y){...})(A,B); Mean in JavaScript
How to Run JavaScript Inside Swift Code
JavaScript in Wkwebview - Evaluatejavascript VS Adduserscript