Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting access to the JSON data in a object

My JSON:

const tests = {
"test 1": {
    "name": "name 1",
    "last name": "prid",
},
"test 2": {
    "name": "name 1",
    "last name": "prid",
},
};

And this is my code:

const obj = {
    enterSom: function(name) {
        console.log(name)
    },

    enterName: function(tests) {
        for (test in tests) {
            let name = test["name"]

            this.enterSom(name)
        }
    },
};

The results:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

undefined
undefined

When I create something like this:

// first case
console.log(tests["test 1"]["name"])
// result -> name 1

// second case
for (test in tests) {
    console.log(test)
}
// result -> test 1
// result -> test 2

And when I extract the loop from my code:

for (test in tests) {
    console.log(test["name"])
}
// result -> undefined
// result -> undefined

How can I get the JSON data when the data are nested like this?

>Solution :

Your code is fine. Only for (key in obj) and not for (value in obj)

const tests = {
  "test 1": {
    "name": "name 1",
    "last name": "prid",
  },
  "test 2": {
    "name": "name 2",
    "last name": "prid",
  },
};


const obj = {
  enterSom: function(name) {
    console.log(name)
  },

  enterName: function(tests) {
    for (test in tests) {
      let name = tests[test]["name"]

      this.enterSom(name)
    }
  },
};

obj.enterName(tests);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading