我有一个json,并想过滤一个关键的多个属性作为完全匹配。
我尝试了以下方法:
let data = [{
"name": "Product 2",
"link": "/stock/product2",
"category": "234",
"description": ""
}, {
"name": "Product 1",
"link": "/stock/product1",
"category": "1231",
"description": ""
}, {
"name": "Product 3",
"link": null,
"category": "22",
"description": ""
}]
data = data.filter(cv => cv.category === ["22", "234"]);
console.log(JSON.stringify(data))Run Code Online (Sandbox Code Playgroud)
我想用name:Product 2和name:返回对象Product 3。
有什么建议让我[]回来吗?
感谢您的答复!
考虑使用Set.has()为你想要的属性,所以你可以可以O(1)查找时间,而不是O(n) (其中n是所需的属性数量)查找时间使用Array.includes() 。
因此,如果您使用集合,则整个过滤器行的整体“时间复杂度”将是O(m) (中m的对象数data),而不是O(mn)使用Array.includes()或具有多个if-else /或检查每个所需属性的条件:
let data = [{
"name": "Product 2",
"link": "/stock/product2",
"category": "234",
"description": ""
}, {
"name": "Product 1",
"link": "/stock/product1",
"category": "1231",
"description": ""
}, {
"name": "Product 3",
"link": null,
"category": "22",
"description": ""
}]
const desiredCategories = new Set(["22", "234"])
data = data.filter(cv => desiredCategories.has(cv.category))
console.log(JSON.stringify(data, null, 2))Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |