我有一个对象数组:
const data = [
{id: "0"},{id: "1"},{id: "2"},{id: "3"},{id: "00"},{id: "01"},{id: "02"},{id: "11"},{id: "20"},{id: "23"},{id: "000"}{id: "013"}{id: "025"}{id: "026"}{id: "110"}{id: "111"}
]
我的预期输出:
<ul>
<li>0
<ul>
<li>00
<ul>
<li>000</li>
</ul>
</li>
<li>01
<ul>
<li>013</li>
</ul>
</li>
<li>02
<ul>
<li>025</li>
<li>026</li>
</ul>
</li>
</ul>
</li>
<li>1
<ul>
<li>11
<ul>
<li>110</li>
<li>111</li>
</ul>
</li>
</ul>
</li>
<li>2
<ul>
<li>20</li>
<li>23</li>
</ul>
</li>
<li>3</li>
</ul>
我的代码到目前为止:
export const NestedList = ({data, level = 1, parent = "0"}) => {
return data
.filter((item:any) => item.id.length === level)
.map((item:any,i:number) => (
<li key={i}>{item.id}{item.id.length < 3 && (
<ul><NestedList data={data.filter((item: any) => item.id.length > level)} level={item.id.length + 1} parent={item.id.slice(0, item.id.length)} /></ul>
)}</li>
));
}
尝试添加一个条件到过滤器中,比如level〉1 && item.id.slice(0,item.id.length-1)=== parent对我不起作用:(有人知道吗?)
2条答案
按热度按时间z2acfund1#
在
filter
中,你可以添加条件来只选择那些id以父id值开始并且级别与当前级别相同的项。PS I删除了这个代码片段的类型。62lalag42#