假設我正在嘗試創建一個“家譜”作為一個 JSON 陣列。
所以我有一個Person物件陣列。
每個Person物件都有一個強制性的name. 每個物件還可以選擇有一個children包含其他Person物件陣列的欄位(也有一個children欄位 - 因此家譜的“深度”基本上可以永遠持續下去。)
如果沒有孩子,該children欄位將只是一個空陣列[]。
例如
const family_name = "The Numbers";
const family = [{
name: "1"
children: [],
},
{
name: "2"
children: [{
name: "2 - 1",
children: [],
},
{
name: "2 - 2",
children: [{
name: "2 - 2 - 1",
children: [],
}, ],
}
],
},
{
name: "3"
children: [{
name: "3 - 1",
children: [],
}, ],
},
]
我需要在“孩子”之前發布“父母”。當我 POST a 時Person,我會id在response.data. 這id需要在直接子項的 POST 中用作 a,parent_id以便子項與父項相關聯。
我還需要首先發布“family_name”,這將回傳一個family_id. 這family_id將僅用parent_id作最頂層的Persons。
例如
axios.post(FAMILY_URL, {"family_name": family_name})
.then((response) => {
// Promise.all() POST 1, 2, and 3 with their "parent_id" as response.data.family_id
// Promise.all() POST 2-1 and 2-2 with their "parent_id" as 2's response.data.id
// POST 2-2-1 with its "parent_id" as 2-1's response.data.id
// POST 3-1 with its "parent_id" as 3's response.data.id
})
但是如果Person物件的數量和深度未知,代碼會是什么樣子呢?我必須利用遞回函式,對嗎?
我還想對所有“兄弟姐妹”使用 Promise.all()
uj5u.com熱心網友回復:
你想遞回地遍歷資料結構,一路積累承諾
// fake axios, ignore this bit
const FAMILY_URL="family-url",axios={post:async(a,o)=>(console.log(`POST ${a}`,o),{data:{id:`${a===FAMILY_URL?"":`${o.parent_id}-`}${Math.ceil(100*Math.random())}`}})};
// resolves an individual person by posting their details with a given
// parent ID, then doing the same for any children
const savePerson = async (parent_id, { name, children }) => {
// get this person's ID
const { data: { id } } = await axios.post("person-url", {
name,
parent_id
})
return {
id, // assign the ID for visibility
name,
// pass this person's ID as the children's parent
children: await savePeople(id, children)
}
}
// resolves an array of people given a "parent ID"
const savePeople = (parent_id, people) =>
Promise.all(people.map(person => savePerson(parent_id, person)))
// Top-level family helper
const saveFamily = async (family_name, family) => {
const { data: { id } } = await axios.post(FAMILY_URL, { family_name })
// resolve all the people in the family array
return savePeople(id, family)
}
// minified
const family = [{"name":"1","children":[]},{"name":"2","children":[{"name":"2 - 1","children":[]},{"name":"2 - 2","children":[{"name":"2 - 2 - 1","children":[]}]}]},{"name":"3","children":[{"name":"3 - 1","children":[]}]}]
saveFamily("Smith", family).then(console.info)
.as-console-wrapper { max-height: 100% !important; }
uj5u.com熱心網友回復:
我會使用 BFS 演算法來處理它。例子:
function postFamily(family) {
const queue = [];
queue.unshift(...family);
while (queue.length) {
const cur = queue.pop();
// HERE IS YOUR LOGIC RELATED TO THE CURRENT NODE
// FOR EXAMPLE:
axios.post('*FAMILY URL*', cur);
for (const child of cur) {
queue.unshift(child);
}
}
}
我不清楚想要的結果,但如果它會有所幫助,我很高興。祝你今天過得愉快!
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/328818.html
標籤:javascript 递归 公理
