user2028856
user2028856

Reputation: 3183

Loop through json object and sort in order

Currently I have a small piece of code which loops through a json object:

for (var key in json_object) {
    if (json_object.hasOwnProperty(key)) {
        var value       = key; //e.g. 50_100, 1000_2000, 20_50 etc
    }
}

I'm going to be outputting these values into a list later on. But the problem is that these values aren't in any order right now.

I'd like to be able to have these values sorted out in order. So my question is, is this possible and if so how?

Thanks!

Upvotes: 0

Views: 4922

Answers (3)

Steve Bosman
Steve Bosman

Reputation: 2618

The following fixes eslint issues I found in the other solutions:

var arr = [];
Object.keys(json_object).forEach(function(key) {
  arr.push({
    'key': key,
    'value': json_object[key]
  });  
})

Upvotes: 0

Asaf David
Asaf David

Reputation: 3297

After reading all solutions, I realized my solution was wrong. Object.keys is good for getting an array of keys only, so Mike Brant's solution is correct, although a little fix is needed since value is not a variable there. Finally here's a fixed solution based on his solution + the requested sorting from the comments:

var arr = [];

for (var key in json_object) {
    if (json_object.hasOwnProperty(key)) {
        arr.push({
            'key': key;
            'value': json_object[key];
        });   
    }
}

// this will sort by the first part of the string
arr.sort(function(a, b) {
  return a.key.split('_')[0] - b.key.split('_')[0];  
}

Hope this helps... :-)

Upvotes: 1

Mike Brant
Mike Brant

Reputation: 71384

In javascript, object properties are not guaranteed a specific order, so if you want to maintain order, you would likely need to write the object properties into an array of objects.

That could look like this:

var object_array = [];
// map properties into array of objects
for (var key in json_object) {
    if (json_object.hasOwnProperty(key)) {
        object_array.push({
            'key': key;
            'value': value;
        });   
    }
}
// sort array of objects
object_array.sort(function(a,b) {
    // note that you might need to change the sort comparison function to meet your needs
    return (a.value > b.value);
}

Upvotes: 1

Related Questions