我正在處理以下 JavaScript 物件:
{
"gender": "man",
"jobinfo": {
"type": "teacher"
},
"children": [
{
"name": "Daniel",
"age": 12,
"pets": [
{
"type": "cat",
"name": "Willy",
"age": 2
},
{
"type": "dog",
"name": "Jimmie",
"age": 5
}
]
}
]
}
我想列印出物件中的每個路徑(鍵和陣列索引),包括父物件(即children
應該像其中的所有內容一樣列印)。
gender
jobinfo,
jobinfo.type,
children,
children.0.name,
children.0.age,
children.0.pets,
children.0.pets.0.type,
children.0.pets.0.name,
children.0.pets.0.age,
children.0.pets.1.type,
children.0.pets.1.name,
children.0.pets.1.age
我嘗試了修改此代碼,但它對我不起作用:
function getPath(object) {
for (key in object) {
if (Array.isArray(object[key]) === true) {
console.log(key)
getPath(object[key])
} else if (typeof object[key] === 'object') {
console.log(key)
getPath(object[key])
} else {
console.log(key)
}
}
}
它正在列印 JSON 中的所有鍵,但我正在努力加入路徑,尤其是在嵌套元素中。
uj5u.com熱心網友回復:
這有效:
const data = {"gender":"man","jobinfo":{"type":"teacher"},"children":[{"name":"Daniel","age":12,"pets":[{"type":"cat","name":"Willy","age":2},{"type":"dog","name":"Jimmie","age":5}]}]};
const getPath = (currPath, item) => {
console.log(currPath);
if (Array.isArray(item)) {
item.forEach((el, idx) => getPath(`${currPath}.${idx}`, el));
} else if (typeof item == "object") {
Object.entries(item).forEach(([key, value]) => {
getPath(`${currPath}.${key}`, value);
});
}
};
Object.entries(data).forEach(([key, value]) => {
getPath(key, value);
});
基本上我只是遍歷初始物件中的每個條目,在該階段使用鍵作為路徑并檢查值是物件還是陣列。我總是在函式中列印路徑(以提供您想要的外層),然后遞回內層,根據需要添加到路徑中。
uj5u.com熱心網友回復:
在這個版本中,陣列鍵由諸如“children.0”之類的數字組成,等等,這給出了你想要的結果:
const json = {"gender":"man","jobinfo":{"type":"teacher"},"children":[{"name":"Daniel","age":12,"pets":[{"type":"cat","name":"Willy","age":2},{"type":"dog","name":"Jimmie","age":5}]}]};
function getPath(object, previousPath) {
for (key in object) {
let currentPath = previousPath ? `${previousPath}.${key}` : key
if (Array.isArray(object[key])) {
console.log(currentPath)
getPath(object[key], currentPath)
} else if (typeof object[key] === 'object') {
if (!Array.isArray(object)) { // skipping logging array keys like children.0
console.log(currentPath)
}
getPath(object[key], currentPath)
} else {
console.log(currentPath)
}
}
}
getPath(json)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488748.html
標籤:javascript 数组 json 目的 小路