Reversing a "for" loop in JSON

let stuff;
let file = editJsonFile(`${__dirname}/posts.json`);
var obj = file.get();
console.log(obj)

stuff = "";
for(var item in obj) {
}

I need some help in here. How do i make the “for” loop go backwards? (Like, instead of top-to-bottom, it should do bottom-to-top)
This isn’t a normal array, it’s a json file.

{
  "886364": {
    "idea": "gdffgfd",
    "description": "fdggfd",
    "username": "aa"
  },
  "1438089": {
    "idea": "test",
    "description": "fdfdssffds",
    "username": "hey"
  }
}

See Loop through an array backward in JavaScript – Techie Delight.

the for … in method doesn’t process them in any particular order. With array loops and such, as Stylix linked, you can do it in order or reverse order quite easily.

It might be better to make an array of objects rather than an object of objects, so you can do this:

var obj = [
   {
    "id":"886364", 
    "idea": "gdffgfd",
    "description": "fdggfd",
    "username": "aa"
  },
  {
    "id":"1438089",
    "idea": "test",
    "description": "fdfdssffds",
    "username": "hey"
  }
]

obj.reverse();

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

This console logs the 1438089 object, followed by the 886364 object. If you commented out the “obj.reverse();” function, it would do it the other way around.

Hope that helps!

At first glance, I would have given the following piece of code if you wish to keep it as an object of objects:

for (let [key, value] of Object.keys(obj).reverse()) {
  ...
}

All this does is create an array of arrays, with each sub-array containing a key and it’s value, then reverses it, and then loops through that.

However, this will actually only work if all your keys are strings and cannot be interpreted as numbers in any way. But your keys seem to be numbers, so no matter how you order them in the original object, they will always be iterated over in ascending order, and thus in the above code they will be iterated over in descending order. This is due to these object property ordering rules. If this is your intended behaviour, go ahead and use the code I provided - otherwise, you’ll have to either try using Maps, which guarantee insertion order when being iterated over, or use arrays as suggested above.

Happy glitching :smiley:

You could force it to only view them as strings though, right? With the toString() function- would that work?

I already tried that, and it doesn’t work… the semicolon is apparently “not a valid” character in my code.

btw i get my data in the for() loop as JSON.stringify(obj[i].id), if that contributes

it returns a JSON object. When i try to use JSON.stringify() on it, it literally does nothing and returns the same thing.

This seems to work for me:

image

And the code / output:

when i do res.send(variable of the saved item) it just sends a blank screen

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.