[英]How to remove empty arrays in a nested array/object?
我有一個對象數組,這些對象本身就有數組。 我想遍歷對象並刪除我擁有的任何空數組。 對象如下圖:
let a=[{children:[{children:[1,2]},{children:[5,6]}]},
{children:[{children:[]},{children:[5,6]}]},
{children:[{children:[]},{children:[]}]},
{children:[]}]
我試圖通過應用下面的代碼來達到預期的結果,但我收到一條錯誤消息,說無法讀取未定義的屬性“子級”。
function removeEmpty(array){
for(var i=array.length-1;i>=0;i--){
if(array[i].children){
if(array[i].children.length){
for(var j=array[i].children.length-1;j=>0;j--){
if(array[i].children[j].children){
removeEmpty(array[i].children[j])
}else{
array[i].splice[j,1]
}
}
if(!array[i].children.length){
array.splice(i,1)
}
}else{
array.splice(i,1)
}
}
}
}
removeEmpty(a)
預期結果:
expected outcome =[{children:[{children:[1,2]},{children:[5,6]}]},
{children:[{children:[5,6]}]}]
如果我可以對現有代碼進行調整或使用不同的方法,請告訴我。 謝謝你。
為了實現您的目標,您可以使用.reduce()方法。
const a = [{ children: [{ children: [1, 2] }, { children: [5, 6] }] }, { children: [{ children: [] }, { children: [5, 6] }] }, { children: [{ children: [] }, { children: [] }] }, { children: [] } ] const b = a.reduce((previousValue, currentValue) => { const data = [] if (currentValue.children.length > 0) { currentValue.children.forEach((e) => { if (e.children.length > 0) data.push(e); }); } if (data.length > 0) previousValue.push({children: data}); return previousValue; }, []); console.log(b);
這是一個 prune 函數,用於減少具有children
的node
。 只需確保將傳入數據包裝在帶有children
的節點中即可。
對於每個節點子節點,您可以根據子節點數過濾子節點。
const data = [ { children: [{ children: [1,2] }, { children: [5,6] }] }, { children: [{ children: [] }, { children: [5,6] }] }, { children: [{ children: [] }, { children: [] }] }, { children: [] }, ]; const prune = (node, key = 'children') => node[key].reduce((prev, curr) => (children => children.length ? { [key]: [...prev[key], { [key]: children }] } : prev) (curr[key].filter(child => child[key].length)), { [key]: [] }); const tree = prune({ children: data }); tree.children.forEach(child => console.log(JSON.stringify(child)));
.as-console-wrapper { top: 0; max-height: 100% !important; } .as-console-row-code { font-size: smaller !important; }
var updatedArray = children.filter(item => item.children.length > 0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.