我有這樣一個表(或資料結構)
有一個parentIdeaId是指ideas表中的id。
這是我的非結構化資料(請記住這是資料庫中的現有資料,不是已經存在的資料,所以我必須在某些條件下先查詢這個資料)
[{}。
"id": "1",
"title": "Title 1"、
"parentIdeaId": null
},{
"id": "2",
"title": "Title 2"、
"parentIdeaId": 1
},{
"id": "3",
"title": "Title 3"、
"parentIdeaId": 2
},{
"id": "4",
"title": "Title 4"、
"parentIdeaId": null
}]
我還做了一個函式來查找資料(我在實際代碼中使用了Prisma)
function find({ id }) {
return prisma.idea.findUnique({
where: {
id
}
});
}
還有一個函式來查找子代
function responseIdeas({ parentIdeaId }) {
return prisma.idea.findMany({
where: {
parentIdeaId
}
});
}
我希望資料只被過濾為鏈接資料(通過它們的parentIdeaId),所以如果我查詢id "1",結果將是
[{
"id"。"1",
"title": "Title 1",
"parentIdeaId": null。
},{
"id": "2",
"title": "標題2"。
"parentIdeaId": 1.
}{
"id": "3",
"title": "Title 3",
"parentIdeaId": 2.
}]
id: "4"沒有被插入,因為它與它的父輩沒有關系
const data = [
{
id: "1"/span>,
title: "Title 1",
parentIdeaId: null。
},
{
id: "2"/span>,
title: "Title 2",
parentIdeaId: 1, parentIdeaId.
},
{
id: "3",
title: "Title 3",
parentIdeaId: 2, parentIdeaId.
},
{
id: "4",
title: "Title 4",
parentIdeaId: nullfunction find({ id }) {
return data.find(e => e.id ==id) 。
}
function responseIdeas({ parentIdeaId }) {
return data.filter(e => e.parentIdeaId == parentIdeaId) 。
}
async function detail({ id }) {
const findChildren = async({ id })=> {
const idea = await find({ id })。
const responses = await responseIdeas({ parentIdea: id }) 。
if (response.length !== 0) {
const resolveResponses = await Promise.all(
responses.map(async ({ id }) => findChildren({ id })
);
return [ide, ...resolveResponses];
}
return { ...idea };
};
return findChildren({ id })。
}
async function run() {
const result = await detail({ id: "1" }) 。
console.dir(result, { depth: null })。)
}
run();
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
但它最終是這樣的
[/span>
{>
"id": "1",
"title": "Title 1"、
"parentIdeaId": null
},
[]。
{
"id": "2",
"title": "Title 2"、
"parentIdeaId": 1
},
{
"id": "3",
"title": "Title 3"、
"parentIdeaId": 2
}
]
]
我在哪里弄錯了?謝謝
uj5u.com熱心網友回復:
findChildren可能會回傳一個陣列,因為你回傳的是Promise.all() ->,這是一個陣列的承諾,其中一些承諾可能是陣列。
所以你可以使用concat將結果合并到主陣列中,例如像這樣https://codesandbox.io/s/quizzical-sun-c4khx?file=/src/index.js
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/319294.html
標籤:
上一篇:Nodejs遞回函式完成后執行

