NewBee NewBee -3 years ago 120
JSON Question

Sorting JSONarray by nested property

I am trying to sort array of JSON values, but the property to sort is nested within the JSON object. For this example the sort is to be done using data.nested-name.

I tried using https://stackoverflow.com/a/8175221/2053159 but without any success.

[
{
name: 'a75',
data: {nested-name:"zz\, Hello// There="}},
{
name: 'z32',
data: {nested-name:"aa\, Hello// There="}},
];


expected output ->

[
{
name: 'a75',
data: {nested-name:"aa\, Hello There="}},
{
name: 'z32',
data: {nested-name:"zz\, Hello There="}},
];


Nested name do contain lot of back and forward slashes and other special characters.
I don't use external libraries, please provide solutions using native JavaScript.

Answer Source

Assuming arr is your array, you can sort like so:

arr.sort( ( a, b ) => a.data[ "nested-name" ] > b.data[ "nested-name" ] )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download