Reputation: 952
I have a Node.js script that reads and parses the content of a JSON file and iterates through the elements of its root array; when I try to inspect the objects of such iteration I am faced with some unexpected result; the object being iterated seems to be the index of the element being iterated. Here is the script:
if (process.argv.length != 3) {
console.log("Usage: node chooseAdAmongAds.js /path/to/ads.json");
process.exit(9);
}
fs = require("fs");
var content = fs.readFileSync(process.argv[2], "utf8")
var ads = JSON.parse(content);
for (ad in ads) {
console.log(ad);
}
The JSON file:
[
{
"impressions": 131,
"ID": 514,
"investment": 2
},
{
"impressions": 880,
"ID": 451,
"investment": 5
},
{
"impressions": 135,
"ID": 198,
"investment": 9
},
{
"impressions": 744,
"ID": 262,
"investment": 8
},
{
"impressions": 234,
"ID": 954,
"investment": 19
},
{
"impressions": 673,
"ID": 274,
"investment": 12
},
{
"impressions": 442,
"ID": 734,
"investment": 6
},
{
"impressions": 453,
"ID": 982,
"investment": 5
},
{
"impressions": 55,
"ID": 275,
"investment": 5
},
{
"impressions": 628,
"ID": 524,
"investment": 1
}
]
And the console output:
iMac-di-Michele:Node.js michele$ node chooseAdAmongAds.js example.json
0
1
2
3
4
5
6
7
8
9
iMac-di-Michele:Node.js michele$
Why does this happen?
Upvotes: 1
Views: 603
Reputation: 191749
for...in
loops over enumerable properties of an Object and arrays are objects. You should not use for...in
for array iteration
Instead, use Array constructs for iteration such as .forEach
, or just use a for
loop and access the array element by its index.
ads.forEach(function (ad) {
console.log(ad)
})
Upvotes: 2