代码审查:在 Javascript 中简洁地深度过滤对象数组

一段时间以来,我一直在尝试过滤对象数组,但我似乎无法真正掌握它。虽然我通常最终都会得到可以工作的代码,但对我来说它看起来并不像优雅的代码。因此,我非常感谢代码审查和一些提示!


示例: 我目前正在为一家在线商店开发此示例,我需要根据 id 从对象数组中检索产品详细信息。


这是我的辅助函数:


function getItemDetails(id) {

        var getCategory = shelf.filter(obj => obj.articleList.some(cat => cat.id === id));

        var getArticleList = getCategory[0].articleList;

        var getItem = getArticleList.filter(item => item.id == id);

        return getItem 

}

步骤:在第一步中,我尝试过滤数组,但它会返回相应项目的shelf整个数组。articleList


因此,我用相同的标准再次过滤了结果,它有效,但对我来说它看起来非常多余。


这是数据的示例:


const shelf = [{

    "categoryPrice": "2",

    "categoryTitle": "Flyer",

    "articleList": [{

        "id": "1",

        "articleTitle": "Green",

    }, {

        "id": "2",

        "articleTitle": "Blue",

    }],

}, {

    "categoryPrice": "3",

    "categoryTitle": "Post card",

    "articleList": [{

        "id": "3",

        "articleTitle": "Purple"

    }, {

        "id": "4",

        "articleTitle": "Yellow",

    }]

}]


ABOUTYOU
浏览 144回答 3
3回答

烙印99

这可能更适合代码审查,但如果问题只是“如何使其更简洁”,我会建议如下所示:const shelf = [{  "categoryPrice": "2",  "categoryTitle": "Flyer",  "articleList": [{    "id": "1",    "articleTitle": "Green",  }, {    "id": "2",    "articleTitle": "Blue",  }],}, {  "categoryPrice": "3",  "categoryTitle": "Post card",  "articleList": [{    "id": "3",    "articleTitle": "Purple"  }, {    "id": "4",    "articleTitle": "Yellow",  }]}]const findItem = function(shelves, id) {  return shelves.flatMap((shelf) => shelf.articleList).find((article) => article.id == id) || null;}console.log(findItem(shelf, 1));console.log(findItem(shelf, 3));上面的示例连接所有文章列表,然后在该数组中搜索具有提供的 ID 的文章。性能方面?不是最好的,但您要求一些简洁的东西,这大约是给定数据结构所希望的尽可能简洁。

RISEBY

这段代码的复杂度是 O(1),这意味着查找 perarticle.id是常数。但是它会使用更多内存。为了节省内存,我使用了WeakMap,只要你使用同一个shelf变量,它就不会重新计算它。但一旦替换它,它也会从缓存中消失。const shelf = [{  "categoryPrice": "2",  "categoryTitle": "Flyer",  "articleList": [{    "id": "1",    "articleTitle": "Green",  }, {    "id": "2",    "articleTitle": "Blue",  }, {    "id": "3",  //  Added    "articleTitle": "Violet",  }],}, {  "categoryPrice": "3",  "categoryTitle": "Post card",  "articleList": [{    "id": "3",    "articleTitle": "Purple"  }, {    "id": "4",    "articleTitle": "Yellow",  }],}];const findItems = function(shelves, id) {  if (!findItems._map) {    // Create computation cache holder    // Weak map will make sure, that if the object is disposed, it can be garbage collected, with it will be gone its cache too! (That is awsome!)    findItems._map = new WeakMap();  }  if (!findItems._map.has(shelves)) {    // For every shelves object, we will create a new Map containing all mapped values.    const map = new Map();    findItems._map.set(shelves, map);    shelves.forEach(shelf => {      shelf.articleList.forEach(article => {        if (!map.has(article.id)) {          // If list is not yet created create it with the article          return map.set(article.id, [ article ]);        }                // If it exists, add to it        map.get(article.id).push(article);      });    });  }  return findItems._map.get(shelves).get(id);}console.log(findItems(shelf, "1"));console.log(findItems(shelf, "3"));

波斯汪

你可以通过循环两次来逃脱。一次用于外部数组,一次用于articleList数组const findItem = (id) =>    shelf.reduce((acc, current) => {        const found = current.articleList.find((x) => x.id === id);        if (found) return [...acc, found];        return acc;    }, []);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript