JavaScript中如何正确获取嵌套JSON对象中的数据?
解决嵌套对象遍历获取值的问题
你遇到的问题核心是for...in循环遍历对象时,循环变量拿到的是对象的键名(字符串类型),不是对应的值。
看你的代码:
for (test in tests) { let name = test["name"] // test是"test 1"这类字符串,字符串没有name属性,所以返回undefined this.enterSom(name) }
要正确获取嵌套对象里的name值,得先通过键名拿到对应的子对象,再访问它的name属性:
修正后的enterName方法
enterName: function(tests) { for (const testKey in tests) { // 通过键名拿到子对象 const testObj = tests[testKey]; const name = testObj["name"]; this.enterSom(name); } },
更简洁的写法(用Object.values)
如果不需要用到键名,直接遍历对象的所有值会更直观:
enterName: function(tests) { // Object.values直接获取tests里的所有子对象 for (const testObj of Object.values(tests)) { this.enterSom(testObj.name); } },
这样调用后就能正确输出两次name 1了。
内容的提问来源于stack exchange,提问作者Maxwell
相关产品推荐
相关产品推荐

