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.
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.
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.