0
{
  "comments": [
    {
      "created_utc": 1622513325,
      "text": "gdhg sgf sddsfsd fdsf"
    },
    {
      "created_utc": 1622513188,
      "text": "sfdg sgf fdgfdg"
    }
   ]
}

How would you iterate over each object to see the text?

Something like..?

  let data = fs.readFileSync(path.resolve(__dirname, 'comments.json'));
  let comments = JSON.parse(data);
  for(var i in comments){
    for(var j in i) {
      console.log("? " + j.text)
    }
  }
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods) methods (both static and on prototype). – Sebastian Simon Jul 10 '21 at 09:51
  • See [Why is using “for…in” for array iteration a bad idea?](/q/500504/4642212) and [What is the difference between ( for… in ) and ( for… of ) statements?](/q/29285897/4642212). – Sebastian Simon Jul 10 '21 at 09:51
  • 1
    `for (var j of comments.comments)` -- no need for nested loops. – Barmar Jul 10 '21 at 09:54
  • Does this answer your question? [What is the difference between ( for... in ) and ( for... of ) statements?](https://stackoverflow.com/questions/29285897/what-is-the-difference-between-for-in-and-for-of-statements) – tevemadar Jul 10 '21 at 10:00

1 Answers1

0

If you know the structure of your JSON will always be a comments object on the first level, containing a list of elements with created_utc and text, you can do as easy as the following code.

You don't need to nest the cycle as you only want to iterate over one list, then read the items and directly access to the text field of each item.

var jsonString = `{
  "comments": [
    {
      "created_utc": 1622513325,
      "text": "gdhg sgf sddsfsd fdsf"
    },
    {
      "created_utc": 1622513188,
      "text": "sfdg sgf fdgfdg"
    }
   ]
}`;

let comments = JSON.parse(jsonString).comments;

comments.forEach(comment => {
  console.log(comment.text);
});
Balastrong
  • 4,336
  • 2
  • 12
  • 31