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

如何在JavaScript的for-in循环中打印JSON对象的属性值?

问题描述

现有以下JavaScript代码,当前for-in循环仅能打印JSON对象的属性名,如何在同一个循环中打印对应的属性值(如John、Stoke、5000、true)?尝试使用object[0].ele和object[0].${ele}的写法获取属性值,但均未成功。

原代码:

/**
 * @class       : file
 * @author      : Shekhar Suman (shekhar0050m@gmail.com)
 * @created     : Thursday Dec 22, 2022 20:02:47 IST
 * @description : file
 */


employee = '[{"firstName": "John", "lastName": "Stoke", "Salary": 5000, "permanentStaff": true}]';
const object = JSON.parse(employee);
//console.log(object[0])
for(var ele in object[0]){
    console.log(`${ele}`);
}
解决方案

为什么之前的写法失败

  • object[0].ele是点操作符的用法,它会把ele当作字面量属性名而非变量,因此会查找对象中名为ele的属性,自然取不到目标值。
  • object[0].${ele}属于语法错误,模板字符串不能直接嵌套在点操作符后。

正确实现方式

方式1:适配原for-in循环,使用方括号访问符

方括号访问符支持通过变量动态获取属性值,修改循环代码即可:

for(var ele in object[0]){
    // 同时打印属性名和对应值
    console.log(`${ele}: ${object[0][ele]}`);
}

方式2:使用Object.entries()遍历键值对(更直观)

Object.entries()会将对象转换为键值对数组,再通过for-of循环解构获取键和值:

for (const [key, value] of Object.entries(object[0])) {
    console.log(`${key}: ${value}`);
}

两种方式运行后都会输出:

firstName: John
lastName: Stoke
Salary: 5000
permanentStaff: true

内容的提问来源于stack exchange,提问作者Shekhar Suman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:20:15