Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting JavaScript Object by key value Recursively

Sort the objects by keys whose value is also an object and sort that internal object as well i.e sort the object recursively. Sorting should be as per key.

I looked into Stackoverflow's other questions but None of them is for Object Recursive Sorting.

Question I looked into:

Sorting JavaScript Object by property value

Example:

input = {
    "Memo": {
        "itemAmount1": "5",
        "taxName1": "TAX",
        "productPrice1": "10",
        "accountName1": "Account Receivable (Debtors)"
    },
    "Footer": {
        "productDescription2": "Maggie",
        "itemQuantity2": "49.5",
        "accountName2": "Account Receivable (Debtors)",
        "taxName2": "TAX"
    },
    "Header": {
        "itemDiscount3": "10",
        "accountName3": "Account Receivable (Debtors)",
        "productPrice3": "10",
        "taxName3": "TAX"
    }
}

Output

output = {
    "Footer": {
        "accountName2": "Account Receivable (Debtors)",
        "itemQuantity2": "49.5",
        "productDescription2": "Maggie",
        "taxName2": "TAX"
    },
    "Header": {
        "accountName3": "Account Receivable (Debtors)",
        "itemDiscount3": "10",
        "productPrice3": "10",
        "taxName3": "TAX"
    },
    "Memo": {
        "accountName1": "Account Receivable (Debtors)",
        "itemAmount1": "5",
        "productPrice1": "10",
        "taxName1": "TAX"
    }
}

It is not necessary that it is 2 level object hierarchy it may contain n level of object hierarchy which need to be sorted.

like image 600
ksr89 Avatar asked Jun 09 '26 13:06

ksr89


2 Answers

I think what @ksr89 means is that when we apply a for - in loop, we get keys in sorted order. I think this is a valid use case especially in the development of Node.js based ORMs

The following function should work and is I think what you are looking for.

 input = {
    "Memo": {
        "itemAmount1": "5",
        "taxName1": "TAX",
        "productPrice1": "10",
        "accountName1": "Account Receivable (Debtors)"
    },
    "Footer": {
        "productDescription2": "Maggie",
        "itemQuantity2": "49.5",
        "accountName2": "Account Receivable (Debtors)",
        "taxName2": "TAX"
    },
    "Header": {
        "itemDiscount3": "10",
        "accountName3": "Account Receivable (Debtors)",
        "productPrice3": "10",
        "taxName3": "TAX"
    }
}
window.sortedObject = sort(input);

function sort(object){
    if (typeof object != "object" || object instanceof Array) // Not to sort the array
        return object;
    var keys = Object.keys(object);
    keys.sort();
    var newObject = {};
    for (var i = 0; i < keys.length; i++){
        newObject[keys[i]] = sort(object[keys[i]])
    }
    return newObject;
}
for (var key in sortedObject){
    console.log (key);
    //Prints keys in order
}
like image 166
Gaurav Ramanan Avatar answered Jun 11 '26 04:06

Gaurav Ramanan


I was on this page to write the following information. The code is based on Gaurav Ramanan's answer, but handles arrays and null differently.

Comparing JSON

To compare data from JSON files you may want to have them formatted the same way

  • from javascript: JSON.stringify(JSON.parse(jsonString), null, '\t') the last parameter could also be a number of spaces the last 2 parameters are optional (minified output if absent)
  • from Visual Studio Code: with the Prettify JSON extension

Verify indentation (i.e. TABs) and line endings (i.e. Unix). Also, keys may be recursively sorted during formatting.

Sorting keys with javascript:

const {isArray} = Array
const {keys} = Object

function sortKeysRec(obj) {
    if (isArray(obj)) {
        const newArray = []
        for (let i = 0, l = obj.length; i < l; i++)
            newArray[i] = sortKeysRec(obj[i])
        return newArray
    }
    if (typeof obj !== 'object' || obj === null)
        return obj
    const sortedKeys = keys(obj).sort()
    const newObject = {}
    for (let i = 0, l = sortedKeys.length; i < l; i++)
        newObject[sortedKeys[i]] = sortKeysRec(obj[sortedKeys[i]])
    return newObject
}

Ensure unix line endings with javascript: jsonString.replace(/\r\n/ug, '\n').

like image 25
Rivenfall Avatar answered Jun 11 '26 05:06

Rivenfall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!