Home > Software engineering >  Getting access to the JSON data in a object
Getting access to the JSON data in a object

Time:07-25

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:

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?

CodePudding user response:

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);

  • Related