0

I have the following data:

const temp = {
    "_id" : "5def6486ff8d5a2b1e52fd5b",
    "data" : {
        "files" : [
            {
                "path" : "demo1.cpp",
                "lines" : [
                    {
                        "line" : 18,
                        "count" : 0
                    }
                ]
            },
            {
                "path" : "file2/demo2.cpp",
                "lines" : [
                    {
                        "line" : 9,
                        "count" : 0
                    }
                ]
            }
        ]
    }
}

Now, I want to access the path, and line variable inside each of the files. I am still learning using JS and pretty new with Object.keys.

I have this: Object.keys(temp.data.files).forEach(file => console.log(file));

This simply prints 0 and 1. Where am I going wrong in this?

John Lui
  • 1,434
  • 3
  • 23
  • 37
  • Object.keys expects an Object but you're passing an array, just remove that and directly do `temp.data.files.forEach(file => console.log(file));` – Ramesh Reddy Dec 11 '19 at 12:08
  • `temp.data.files.forEach(file => console.log(file.path, file.lines, file.lines[0].line))` – adiga Dec 11 '19 at 12:09
  • You are getting 0 and 1, because when you call Object.keys() with an array, it returns an array of the indices – Ryan Sparks Dec 11 '19 at 12:17

1 Answers1

0

This is because temp.data.files is an array. Object.keys is used to loop through Object.

Try this:

 const temp = {
    "_id": "5def6486ff8d5a2b1e52fd5b",
    "data": {
      "files": [
        {
          "path": "demo1.cpp",
          "lines": [
            {
              "line": 18,
              "count": 0
            }
          ]
        },
        {
          "path": "file2/demo2.cpp",
          "lines": [
            {
              "line": 9,
              "count": 0
            }
          ]
        }
      ]
    }
  }
  temp.data.files.forEach(file => console.log("path ", file.path, " lines ", file.lines));
Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51