可以使用以下几种方法遍历 JSON 对象:for...in 循环Object.keys() 和 forEach()Object.entries() 和 forEach()JSON.stringify() 和 forEach()

JSON(JavaScript Object Notation)是一种轻量级的文本格式,用于表示对象和数组。要遍历 JSON 对象,您可以使用以下几种方法:
<code>const person = {
name: "John Doe",
age: 30,
occupation: "Software Engineer"
};
for (const key in person) {
console.log(key, person[key]);
}
// 输出:
// name John Doe
// age 30
// occupation Software Engineer</code><code>const keys = Object.keys(person);
keys.forEach(key => {
console.log(key, person[key]);
});
// 输出:
// name John Doe
// age 30
// occupation Software Engineer</code><code>Object.entries(person).forEach(([key, value]) => {
console.log(key, value);
});
// 输出:
// name John Doe
// age 30
// occupation Software Engineer</code><code>const personJSON = JSON.stringify(person);
JSON.parse(personJSON).forEach(item => {
console.log(item.key, item.value);
});
// 输出:
// name John Doe
// age 30
// occupation Software Engineer</code>选择遍历 JSON 对象的方法取决于您的具体需求和数据结构。对于简单的对象,for...in 循环或 Object.keys() 方法通常就足够了。对于嵌套或复杂的 JSON 结构,Object.entries() 或 JSON.stringify() 方法可能更适合。
以上就是js怎么遍历json对象的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号