我有一個 javascript 物件,如下所示:
let hogwartsHeirarchy = {
Headmaster: [
{
name: "Professor Dumbledore",
key: 1,
Headmistress: [
{
name: "Minerva McGonagall",
key: 2,
StandByProfessor: [
{
name: "Rubeus Hagrid",
subject: "Potions Master",
key: 3,
Professor: [
{ name: "Horace Slughorn", key: 4 },
{ name: "Severus Snape", key: 4 },
],
},
{
name: "Alastor Moody",
subject: "Defense Against the Dark Arts",
key: 3,
Professor: [
{ name: "Remus Lupin", key: 4 },
{ name: "Gilderoy Lockhart", key: 4 },
],
},
],
},
],
},
],
};
我想列印/獲取每個節點值 [headmaster, headmastress,..] 及其相應的子值。我嘗試了各種方法,例如使用 for 回圈、遞回等回圈遍歷陣列,但不幸的是我無法從節點中獲取任何值。請幫忙。
例如:我用過這個:
printArray(hogwartsHeirarchy);
function printArray(arr){
for(var i = 0; i < arr.length; i ){
if(arr[i] instanceof Array){
console.log("true: ");
console.log("intermediate one : ",arr[i]);
printArray(arr[i]);
}else{
console.log("final one : ",arr[i]);
}
}
}
這些值可以以這種格式顯示:
Headmaster - name : Professor Dumbledore, key : 1
.
.
StandByProfessor - name : Robeus Hagrid, subject : Potion Master, key : 3
StandByProfessor - name : Alastor Moody, subject : Defence against the dark arts, key : 3
.
.
Professor - ...
Professor - ...
Professor - ...
Professor - ...
uj5u.com熱心網友回復:
我建議重組,以便始終使用相同的密鑰訪問下屬,從而可以非常簡單地訪問。我也做了它,所以每個節點都是一個人,頂部沒有不是人的物體。我留下了變數名,但它現在直接指代鄧布利多。
let hogwartsHeirarchy =
{
name: "Professor Dumbledore",
role: "Headmaster",
key: 1,
subordinates: [
{
name: "Minerva McGonagall",
role: "Headmistress",
key: 2,
subordinates: [
{
name: "Rubeus Hagrid",
role: "StandByProfessor",
subject: "Potions Master",
key: 3,
subordinates: [
{ name: "Horace Slughorn", key: 4, role: "Professor" },
{ name: "Severus Snape", key: 4, role: "Professor" },
],
},
{
name: "Alastor Moody",
role: "StandByProfessor",
subject: "Defense Against the Dark Arts",
key: 3,
subordinates: [
{ name: "Remus Lupin", key: 4, role: "Professor" },
{ name: "Gilderoy Lockhart", key: 4, role: "Professor" },
],
},
],
},
],
};
function visitStaff(staffMember) {
if (staffMember.subordinates) {
for (const subordinate of staffMember.subordinates) {
visitStaff(subordinate);
}
}
console.log("Staff member:", staffMember);
}
visitStaff(hogwartsHeirarchy);
在設定資料結構時,重要的是要考慮如何訪問它,以及它的定義部分是什么。在這種情況下,人是節點,(從屬)關系是圖的邊。
在你的原始代碼中,你有一個物件{ Headmaster: [...] }——它代表什么?它是一個人嗎?不; 是關系嗎?有點,但沒有。它定義了一些關于Dumbledoor,他是校長,但不是誰或什么他是校長的。所以它實際上只是描述了鄧布利多的角色/職位,所以它作為一個人的財產更有意義。它作為一個物件是多余的。
它有助于對齊您的物件,以便它們都代表某些東西。您應該能夠描述每個物件和陣列是什么。
uj5u.com熱心網友回復:
您可以從物件中洗掉已知鍵并獲取型別層次結構,然后迭代屬性并僅在型別存在時回傳型別、名稱、主題和鍵的元組。
const
getValues = (object, type) => [
...(type ? [[type, object.name, object.subject || '', object.key]] : []),
...Object
.keys(object)
.filter(k => !['name', 'subject', 'key'].includes(k))
.flatMap(k => object[k].flatMap(o => getValues(o, k)))
],
hogwartsHierarchy = { Headmaster: [{ name: "Professor Dumbledore", key: 1, Headmistress: [{ name: "Minerva McGonagall", key: 2, StandByProfessor: [{ name: "Rubeus Hagrid", subject: "Potions Master", key: 3, Professor: [{ name: "Horace Slughorn", key: 4 }, { name: "Severus Snape", key: 4 }] }, { name: "Alastor Moody", subject: "Defense Against the Dark Arts", key: 3, Professor: [{ name: "Remus Lupin", key: 4 }, { name: "Gilderoy Lockhart", key: 4 }] }] }] }] };
console.log(getValues(hogwartsHierarchy));
.as-console-wrapper { max-height: 100% !important; top: 0; }
uj5u.com熱心網友回復:
給定資料結構:
a) 我假設每種型別的“標題”中只有一個陣列,并且
b) 該陣列將包含一個與其父物件結構相似的物件串列
這是可能的 ...
- 使用
for..of以 - 遍歷物件上的每個鍵,并將它們添加到字串中。因為有包含物件的陣列,
- 我可以遍歷它們,然后
- 做一個遞回回圈。
const hogwartsHierarchy = { Headmaster: [{ name: "Professor Dumbledore", key: 1, Headmistress: [{ name: "Minerva McGonagall", key: 2, StandByProfessor: [{ name: "Rubeus Hagrid", subject: "Potions Master", key: 3, Professor: [{ name: "Horace Slughorn", key: 4 }, { name: "Severus Snape", key: 4 }] }, { name: "Alastor Moody", subject: "Defense Against the Dark Arts", key: 3, Professor: [{ name: "Remus Lupin", key: 4 }, { name: "Gilderoy Lockhart", key: 4 }] }] }] }] };
function printAllWithChilds(obj, prevProp) {
let listItem = (prevProp) ? ' -- ' prevProp : '';
for (const property in obj) { // 1
if (obj[property] instanceof Array) {
obj[property].forEach((child_obj) => { // 3
listItem = printAllWithChilds(child_obj, property); // 4
});
} else {
listItem = `, ${property}: ${obj[property]}`; // 2
}
}
return listItem;
}
let listStr = printAllWithChilds(hogwartsHierarchy);
console.log(listStr);
老實說,我會hogwartsHierarchy按照一種資料庫結構分成更小的部分,primary_key每個人的位置都是獨一無二的。這些陣列沒有多大意義,直到您查看變數professors以及它們各自的belongs_to鍵如何對應于standbyprofessors,您可以看到“Horace Slughorn”屬于“Rubeus Hagrid”。
const headermaster = {
name: "Professor Dumbledore",
primary_key: 1
};
const headmistress = {
name: "Minerva McGonagall",
primary_key: 2,
belongs_to: 1
};
const standbyprofessors = [{
name: "Rubeus Hagrid",
subject: "Potions Master",
primary_key: 3,
belongs_to: 2
},
{
name: "Alastor Moody",
subject: "Defense Against the Dark Arts",
primary_key: 4,
belongs_to: 2
}
];
const professors = [{
name: "Horace Slughorn",
primary_key: 5,
belongs_to: 3
},
{
name: "Severus Snape",
primary_key: 6,
belongs_to: 3
},
{
name: "Remus Lupin",
primary_key: 7,
belongs_to: 4
},
{
name: "Gilderoy Lockhart",
primary_key: 8,
belongs_to: 4
},
];
uj5u.com熱心網友回復:
基于1j01物件模型:
const hogwartsHeirarchy =
{ name: "Professor Dumbledore", role: "Headmaster", key: 1,
subordinates: [{ name: "Minerva McGonagall", role: "Headmistress", key: 2,
subordinates: [
{ name: "Rubeus Hagrid", role: "StandByProfessor", subject: "Potions Master", key: 3,
subordinates: [
{ name: "Horace Slughorn", key: 4, role: "Professor" },
{ name: "Severus Snape", key: 4, role: "Professor" }]},
{ name: "Alastor Moody", role: "StandByProfessor", subject: "Defense Against the Dark Arts", key: 3,
subordinates: [
{ name: "Remus Lupin", key: 4, role: "Professor" },
{ name: "Gilderoy Lockhart", key: 4, role: "Professor" }]}]}]};
const visitStaff = (staffMember) => {
const iter = (obj) => {
const { name, role, key, subordinates } = obj;
const subject = obj.subject ? `, subject: ${obj.subject}` : '';
const line = `${role} - name : ${name}${subject}, key : ${key}`;
const sublines = (Array.isArray(subordinates)) ? subordinates.flatMap((s) => iter(s)) : [];
return [line, ...sublines];
}
return iter(staffMember).join('\n');
}
console.log(visitStaff(hogwartsHeirarchy));
.as-console-wrapper { max-height: 100% !important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/383214.html
標籤:javascript 数组 循环 递归 嵌套
上一篇:創建檔案夾和移動檔案
