我需要一個函式來根據給定的物件結構過濾物件陣列。所以我有這個物件:
{
"2": [
{
"fd_id": 16,
...others
}
],
"3": [
{
"fd_id": 2,
...others
},
{
"fd_id": 3,
...others
}
]
}
我想根據這個物件過濾另一個陣列。像這樣;
const result = products.filter(item => {
// returns array of numbers [1, 2, 3]
const filters = item.filters;
if(filters){
// Here must be refactored
return ((filters.includes(givenObj[2][0].fd_id))
&& (filters.includes(givenObj[3][0].fd_id) || filters.includes(givenObj[3][1].fd_id)));
}
});
但是這個函式必須是動態的。因為輸入物件可能會改變。因此,對于每個父級之間的“&&”,以及每個子級之間的“||” 條件必須適用。謝謝你的幫助。這是示例的鏈接https://jsfiddle.net/cadkt86n/
uj5u.com熱心網友回復:
回圈資料的函式會有所幫助。
我的邏輯
fd_id從groupsusing生成s的串列Array.map- 過濾
products陣列。檢查陣列filters節點中的匹配組合products。條件是fdIdList陣列的每個節點都應該有一個匹配的組合。
作業小提琴
var groups = {
"2": [
{ "fd_id": 16, "fd_fRef": 2, "fd_ad": "35 - 50", "fd_siraNo": 255, "checked": true }
],
"3": [
{ "fd_id": 2, "fd_fRef": 3, "fd_ad": "KURU", "fd_siraNo": 255, "checked": true },
{ "fd_id": 3, "fd_fRef": 3, "fd_ad": "KARMA", "fd_siraNo": 255, "checked": true }
]
}
// Aggregates the list of fd_id s - This wil be an array of arrays
// [[16],[2,3]] => This will be the value
const fdIdList = Object.values(groups).map(a => a.map(b => b.fd_id));
var products = [
{
"id": 1,
"filters": [2, 3, 4, 13, 16, 17, 18, 19, 31, 48, 309, 318],
},
{
"id": 2,
"filters": [2, 3, 4, 13, 15, 17, 18, 19, 31, 48, 309, 318],
}
];
// Check if there is a common element in each node of fdIdList
var result = products.filter(item => {
const filters = item.filters;
if (filters) {
let isFound = true;
fdIdList.forEach(idListNode => {
isFound = isFound && idListNode.filter(value => filters.includes(value)).length > 0;
})
return isFound
}
});
console.log(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/376772.html
標籤:javascript 数组
