使用 JS 中的 Object.keys 遍历多个嵌套的 JSON



我有以下数据:

const temp = {
"_id" : "5def6486ff8d5a2b1e52fd5b",
"data" : {
"files" : [
{
"path" : "demo1.cpp",
"lines" : [
{
"line" : 18,
"count" : 0
}
]
},
{
"path" : "file2/demo2.cpp",
"lines" : [
{
"line" : 9,
"count" : 0
}
]
}
]
}
}

现在,我想访问path,并在每个filesline变量。我仍在学习使用JS,并且使用Object.keys非常新。

我有这个:Object.keys(temp.data.files).forEach(file => console.log(file));

这只打印 0 和 1。我哪里做错了?

这是因为temp.data.files是一个数组。Object.keys 用于循环遍历Object

试试这个:

const temp = {
"_id": "5def6486ff8d5a2b1e52fd5b",
"data": {
"files": [
{
"path": "demo1.cpp",
"lines": [
{
"line": 18,
"count": 0
}
]
},
{
"path": "file2/demo2.cpp",
"lines": [
{
"line": 9,
"count": 0
}
]
}
]
}
}
temp.data.files.forEach(file => console.log("path ", file.path, " lines ", file.lines));

最新更新