[英]filter array from nested array in javascript
我有兩個數組,我需要根據名稱過濾此數組。
const arr1 = ["Saab", "Volvo", "BMW", "Car3", "Car2", "Van", "Bus"];
const arr2 = [
{
name: "Saab",
url: "saab/"
},
{
name: "Volvo",
url: "volvo/",
children:[
{
name: "Van",
url: "van/"
},
{
name: "Bus",
url: "bus/"
},
]
},
{
name: "BMW",
url: "bmw/"
},
{
name: "SUV",
url: "suv/",
children:[
{
name: "Car1",
url: "car1/"
},
{
name: "Car2",
url: "car2/"
},
{
name: "Car3",
url: "car3/"
},
]
}
]
我嘗試使用此代碼。 const result = arr2.filter((item) => arr1.includes(item.name);
這段代碼可以正常工作,但是它不會檢查arr2
子對象,我需要根據arr1
值進行檢查,如果我有子對象,我還需要檢查該名稱。 例如:名稱SUV
在arr1
但是car1
和car2
值不在arr1
,那時候我需要刪除該SUV
對象。
我的輸出應為:
[
{
name: "Saab",
url: "saab/"
},
{
name: "Volvo",
url: "volvo/",
children:[
{
name: "Van",
url: "van/"
},
{
name: "Bus",
url: "bus/"
},
]
},
{
name: "BMW",
url: "bmw/"
},
]
我如何使用javascript
做到這一點,在es6
可以做到嗎?
您可以使用另一個過濾器功能來檢查過濾器功能內的children
。
說明:
item
和item.length
以確保子代存在並且不為空(如果沒有必要,您可以刪除第二item.length
,但是這樣做更安全,因為在大多數情況下,它可以確保子代是數組,並且.every
不會拋出錯誤) .every
和.includes
測試是否所有孩子都在arr1
||
的第二部分 如果第一部分為真,則不執行 !item.children
因為如果第一個替代方法在子項上失敗,它將回arr1.includes(item.name)
的結果上,並且“ SUV”將返回結果 const arr1 = ["Saab", "Volvo", "BMW", "SUV", "Car3", "Van", "Bus"]; const arr2 = [ { name: "Saab", url: "saab/" }, { name: "Volvo", url: "volvo/", children:[ { name: "Van", url: "van/" }, { name: "Bus", url: "bus/" }, ] }, { name: "BMW", url: "bmw/" }, { name: "SUV", url: "suv/", children:[ { name: "Car1", url: "car1/" }, { name: "Car2", url: "car2/" }, { name: "Car3", url: "car3/" }, ] } ]; const result = arr2.filter( (item) => ( (item.children && item.children.length && item.children.every(v => arr1.includes(v.name))) || (!item.children && arr1.includes(item.name)) ) ); console.log(result);
編輯 :滿足要求的固定代碼
EDIT2 :變成了純ES6答案,現在不需要老式
您可以對結果使用foreach並通過最后一種方法檢查項目值(過濾嵌套數組)。
請嘗試這個。
res = arr2.filter(item2 => (arr1.findIndex(item1 => item2['name'] == item1) > -1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.