簡體   English   中英

在對象深處過濾時為空數組

[英]Empty array when filter inside deep an object

我做了這個函數來過濾一個對象數組的深層,但最后結果是空的。 如果我檢查 if 語句中的 console.log ,它會顯示過濾的對象,但 resultPost 返回空值。 我還嘗試將過濾后的值推入一個空數組,但不起作用。

 const post = [{ "name": "new post", "description": "simple desc", "taxonomies": { "categories": { "0": { "term_id": 15 }, "1": { "term_id": 20 }, } } }, { "name": "new post 2", "description": "simple desc 2", "taxonomies": { "categories": { "0": { "term_id": 11 }, "1": { "term_id": 12 }, } } } ]; const filterID = [15, 1]; const resultPost = post.filter(post => { if ((post.taxonomies.categories.filter(postct => postct.term_id === filterID)).length > 0) return post }); console.log(resultPost);

您可以通過匹配taxonomies.categories[id].term_id來過濾帖子,如下所示:

 const post = [{ "name": "new post", "description": "simple desc", "taxonomies": { "categories" : { "0" : { "term_id" : 15 }, "1" : { "term_id" : 20 }, } } }, { "name": "new post 2", "description": "simple desc 2", "taxonomies": { "categories" : { "0" : { "term_id" : 11 }, "1" : { "term_id" : 12 }, } } }]; const filterID = [15,1]; const resultPost = post.filter(item => { const { categories } = item.taxonomies; return Object.keys(categories).reduce((cats, id) => { filterID.includes(categories[id].term_id) && cats.push(id); return cats; }, []).length }); console.log( resultPost)

就像評論中所說的那樣,您不能對對象使用過濾器。 試試這個

const resultPost = post.filter(post => {
    for (let cat in post.taxonomies.categories) { // one way to loop over objects
        // filterId is an array so you can't just use ===
        if (filterID.includes(post.taxonomies.categories[cat].term_id)) return true;
    }
    return false;
});

在過濾器內部,您可以獲取該對象的Object.values ,然后根據您的條件使用some來過濾記錄。 像這樣的東西:

 const post = [{ "name": "new post", "description": "simple desc", "taxonomies": { "categories": { "0": { "term_id": 15 }, "1": { "term_id": 20 }, } } }, { "name": "new post 2", "description": "simple desc 2", "taxonomies": { "categories": { "0": { "term_id": 11 }, "1": { "term_id": 12 }, } } }]; const filterID = [15,1]; const result = post.filter(p=>Object.values(p.taxonomies.categories).some(n=>filterID.includes(n.term_id))); console.log(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM