lodash:使用pickBy过滤对象中的对象

时间:2018-05-31 17:56:35

标签: javascript lodash

我正在尝试使用"lodash": "^4.17.10"过滤对象。

见下面我最小的可行例子:

const obj = {
    "2": {
        "title": "GeForce GTX 1070 SC GAMING ACX 3.0 Black Edition",
        "category": [{
            "term_id": 34,
            "name": "Graphic Card",
            "slug": "graphic-card",
            "term_group": 0,
        }],
        "currency": "$",
        "price": "547.85",
        "watt": "0",
    },
    "3": {
        "title": "GeForce White Edition",
        "category": [{
            "term_id": 32,
            "name": "other-card",
            "slug": "other-card",
            "term_group": 0,
        }],
        "currency": "$",
        "price": "600.85",
        "watt": "0",
    }
}

let allGpuParts = _.pickBy(obj, (value, key) => {
    return _.startsWith(key.category, "graphic-card")
})

console.log("allGpuParts")
console.log(allGpuParts)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

目前您无法返回任何结果。我想只返回具有slu "2":的对象"slug": "graphic-card"

有关如何使用lodash过滤的任何建议吗?

感谢您的回复!

2 个答案:

答案 0 :(得分:1)

您可以使用_.filter_.isMatch找到您要查找的键值对_.some,只表示匹配return true

const obj = {
    "2": {
        "title": "GeForce GTX 1070 SC GAMING ACX 3.0 Black Edition",
        "category": [{
            "term_id": 34,
            "name": "Graphic Card",
            "slug": "graphic-card",
            "term_group": 0,
        }],
        "currency": "$",
        "price": "547.85",
        "watt": "0",
    },
    "3": {
        "title": "GeForce White Edition",
        "category": [{
            "term_id": 32,
            "name": "other-card",
            "slug": "other-card",
            "term_group": 0,
        }],
        "currency": "$",
        "price": "600.85",
        "watt": "0",
    }
}

const isGPU = o => _.isMatch(o, {slug: "graphic-card"});
const allGpuParts = _.filter(obj, ({category}) => category.some(isGPU));

console.log("allGpuParts")
console.log(allGpuParts)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

如果我误解了或者您有任何问题,请告诉我。

答案 1 :(得分:1)

  • category 对象数组,因此您需要以某种方式对其进行迭代,例如:使用Array.prototype.some查找是否有符合条件的项目
  • 您需要检查 slug 本身,而不是测试字符串与对象类别

我保留了 startsWith 测试,尽管您当前的示例也可以使用完全匹配

const graphicCategory = cat => cat.slug.startsWith('graphic-card'); // true or false test

_.pickBy(
    obj, // your object
    value => value.category.some(graphicCategory) // pick if some category has graphic-card
); // {2: { ... }}