我正在尝试使用"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>
正如您目前可以看到的,没有返回任何结果。我只想要回对象"2":,它有弹格"slug": "graphic-card"。
有什么建议吗?如何与房客过滤?
谢谢你的回复!
发布于 2018-05-31 18:15:07
您只需使用_.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>
如果我误解了,或者有什么问题,请告诉我。
发布于 2018-05-31 19:13:19
我保留了一个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: { ... }}https://stackoverflow.com/questions/50630165
复制相似问题