我有這樣的結構:
const tree = [
{
"a": "1",
"children": [
{
"a": "11",
"children": [
{ "a": "111", "p": "me" },
{ "a": "112" }
]
},
{ "a": "111", "p": "me" }
]
},
{ "a": "2" },
{ "text": "3", "p": "me" }
]
而且我正在嘗試通過 過濾樹p: "me",但是,我一直碰到父級并且無法通過它。我想要的輸出是以下幾行:
const res = filter(tree, "p", "me")
console.log(res)
/*
[
{
"a": "1",
"children": [
{
"a": "11",
"children": [
{ "a": "111", "p": "me" },
]
},
{ "a": "111", "p": "me" }
]
},
{ "text": "3", "p": "me" }
]
*/
我嘗試了其他解決方案并對其進行了調整(比如這個),但我很掙扎
uj5u.com熱心網友回復:
檢查我在代碼中的評論。
訣竅是知道何時進入遞回以深入樹中以及何時回傳true/false用于 JSfilter()方法。
const tree = [
{
"a": "1",
"children": [
{
"a": "11",
"children": [
{ "a": "111", "p": "me" },
{ "a": "112" }
]
},
{ "a": "111", "p": "me" }
]
},
{ "a": "2" },
{ "text": "3", "p": "me" }
]
const filter = (array, property, value) => {
// Filter an array...
return array.filter((object) => {
// If an object of the array has a 'children'
if(object.children){
// It goes into recursion to set the filtered 'children'
object.children = filter(object.children, property, value)
// Then returns true if the children array is not empty
return object.children.length
}
// If the object has a 'p' === 'me' (passed as arguments), it returns true (or false to discards the object)
return object[property] === value
})
}
console.log(filter(tree, "p", "me"))
uj5u.com熱心網友回復:
我們可以在一個可重用的深度過濾函式之上構建它,只需傳遞一個謂詞來說明我們是否保留了一個物件。這個使用了deepFilter我的虛擬工具箱中的一個功能:
const deepFilter = (pred) => (xs) =>
xs .flatMap (({children = [], ...rest}, _, __, kids = deepFilter (pred) (children)) =>
pred (rest) || kids.length
? [{...rest, ...(kids.length ? {children: kids} : {})}]
: []
)
const keepProp = (name, value) =>
deepFilter (x => x [name] == value)
const tree= [{a: "1", children: [{a: "11", children: [{a: "111", p:"me"}, {a: "112"}]}, {a: "111", p: "me"}]}, {a: "2"}, {text: "3", p: "me"}]
console .log (keepProp ('p', 'me') (tree))
.as-console-wrapper {max-height: 100% !important; top: 0}
請注意,使用此功能不會損害任何物體。它將您的資料視為不可變的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/507850.html
標籤:javascript 递归 树 树视图
