0

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?

Maxwell
  • 138
  • 1
  • 9
  • Does this answer your question? [How to iterate (keys, values) in JavaScript?](https://stackoverflow.com/questions/34913675/how-to-iterate-keys-values-in-javascript) – luk2302 Jul 24 '22 at 19:20
  • Does this answer your question? [How do I loop through or enumerate a JavaScript object?](https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – Ivar Jul 24 '22 at 19:22

1 Answers1

0

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);
IT goldman
  • 14,885
  • 2
  • 14
  • 28