0

I have got a function which retrieves an object.

This object has a property and a value. The property is numeric and starts at "-30" all the way up to "50"

The problem is that when I loop through this object the browser seems to order it starting at "0" instead of starting at the initial property of "-30"

I need to make sure the order is exactly the same as the object.

var colorOj = {
   "-30":"#111","-29":"#131313", ..etc.., "0":"#333", ..etc.., 
   "50":"#555"
}

function makeList(object){
   for (var i in object) {
      console.log(i); // Returns 0,1,2,3,4,5
      // I need a return of -30,-29,-28,..., 0, 1, 2 ...
   }
}
makeList(colorObj);
Nicolas T
  • 327
  • 1
  • 5
  • 15
  • 1
    Properties in JS objects [don't have any specific order](https://es5.github.io/#x12.6.4). You've to convert your object to array to get a sortable "object". – Teemu Jan 12 '16 at 12:15
  • http://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value/16794116#16794116 – Kaushik Jan 12 '16 at 12:22

2 Answers2

2

As suggested by @Teemu, properties are not stored in any specific order. But you can print them in any order using specific sort function accordingly.

Code

var obj = {};

for (var i = 5; i > -5; i--) {
  obj[i * 10] = i * 10;
}

// Sort and get all keys...
var keys = Object.keys(obj).sort(function(a, b) {
  return parseInt(a) - parseInt(b);
});

console.log(keys)

// Loop over keys to print values of each property
keys.forEach(function(item) {
  console.log(item, obj[item]);
})
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

You can do something like this maybe:

var colorOj = {
   "-30":"#111","-29":"#131313", "0":"#333", 
   "50":"#555"
};

var keys = Object.keys(colorOj).sort(function(a,b){return a - b})

for(var i = 0; i < keys.length;i++){console.log(keys[i])}

This way you can get every key in the object. Then sort it however you like(the sort function in javascript can take a compare function as a parameter look -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)

user3410846
  • 97
  • 1
  • 11