David Rivera
David Rivera

Reputation: 369

Iterate an object on a specific order

I have some JSON like this:

{ 
"a": { "text": "text", "index": 5 },
"b": { "text": "text", "index": 3 },
"c": { "text": "text", "index": 1 },
} 

Now I need to interate this object and call a function on every property of the first level (a, b and c), but I have to do it on order using the "index" property, like "c" first, then "b" and last "a".

However I read that I shouldn't use a for in loop:

A for...in loop iterates over the properties of an object in an arbitrary order (see the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting).

then how I can do this?

Thanks

Upvotes: 3

Views: 3933

Answers (6)

GSSwain
GSSwain

Reputation: 6133

You can use getOwnPropertyNames

let obj = { 
  "a": { "text": "text", "index": 5 },
  "b": { "text": "text", "index": 3 },
  "c": { "text": "text", "index": 1 }
};

function test(p) { 
    console.log(p);
}

Object.getOwnPropertyNames(obj)
      .reverse() 
      .forEach(function(p){
         test(obj[p]);
      });

Upvotes: 2

HubballiHuli
HubballiHuli

Reputation: 777

you can also make use of reverse() method of javascript if you want to access the json items in reverse order.
get the array of all the keys of json using Object.keys()
reverse the array using reverse() method
and finally you can make use of javascript forEach() method to work on the items of the json. Sample code is shown below

let obj = {
"a": { "text": "text", "index": 5 },
"b": { "text": "text", "index": 3 },
"c": { "text": "text", "index": 1 },
}

Object.keys(obj)
            .reverse()
            .forEach(ele => {
              console.log(obj[ele]);
            });

visit This link to know more about reverse() method

Upvotes: 0

StefansArya
StefansArya

Reputation: 2898

The another solution is store the object keys and reverse it, then iterate with the object keys.

var obj = { 
	"a": { "text": "text", "index": 5 },
	"b": { "text": "text", "index": 3 },
	"c": { "text": "text", "index": 1 }
};
var yourFunction = console.log;
var keys = Object.keys(obj);
keys.reverse();
for (var i = 0; i < keys.length; i++) {
	yourFunction(obj[keys[i]]);
}

Upvotes: 0

user9465836
user9465836

Reputation:

You can try the following:

  1. Covert the object to an array with elements in sorted order based on the index.
  2. Than simply forEach() on the sorted properties.

Sort function can be implemented as :

var obj = { 
"a": { "text": "text", "index": 5 },
"b": { "text": "text", "index": 3 },
"c": { "text": "text", "index": 1},
}

 function sortProperties(obj, sortedBy, isNumericSort, reverse) {
            sortedBy = sortedBy || 1; // by default first key
            isNumericSort = isNumericSort || false; // by default text sort
            reverse = reverse || false; // by default no reverse

            var reversed = (reverse) ? -1 : 1;

            var sortable = [];
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    sortable.push([key, obj[key]]);
                }
            }
            if (isNumericSort)
                sortable.sort(function (a, b) {
                    return reversed * (a[1][sortedBy] - b[1][sortedBy]);
                });
            else
                sortable.sort(function (a, b) {
                    var x = a[1][sortedBy].toLowerCase(),
                        y = b[1][sortedBy].toLowerCase();
                    return x < y ? reversed * -1 : x > y ? reversed : 0;
                });
            return sortable; // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
        }
        
        sortProperties(obj, 'index', true, false);

Upvotes: 1

H77
H77

Reputation: 5967

You could,

  1. Get the properties of the object as an array using Object.keys().
  2. Sort the properties of the object using sort().
  3. Use forEach() to iterate through the sorted items (which is executed in ascending order of the array).

var items = {
  "a": {
    "text": "text",
    "index": 5
  },
  "b": {
    "text": "text",
    "index": 3
  },
  "c": {
    "text": "text",
    "index": 1,
  }
};

Object.keys(items).sort(function(a, b) {
  return items[a].index - items[b].index;
}).forEach(doStuff);

function doStuff(key) {
  console.log(items[key]);
}

Upvotes: 6

jcarpenter2
jcarpenter2

Reputation: 5476

Probably you should use Object.keys to get a list of all the properties, sort that list, then iterate over it.

Upvotes: -1

Related Questions