You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:27:26