[英]Filter an complex array with multiple criteria
var sd = {
"searchData": [
{
"description": "ISU ISU",
"tags": {
"portfolio": [
"p1",
"p2",
"p3"
],
"industry": [
"i1",
"i2",
"i3"
]
},
},
{
"description": null,
"tags": {
"portfolio": [
"p1",
"p2",
"p3"
],
"industry": [
"i1",
"i4",
"i5"
]
},
{
"description": null,
"tags": {
"portfolio": [
"p4",
"p5",
"p6"
],
"industry": [
"i1",
"i2",
"i3"
]
},
}
]
} }
I will get this data from a api.我将从 api 获取这些数据。 I want to filter the above with portfolio value of p1 and industry with i1.
我想用 p1 的投资组合值和 i1 的行业过滤上述内容。
I tried using filter but not able to get the required result.我尝试使用过滤器但无法获得所需的结果。 I cannot use other libraries like loadash or undersore.
我不能使用其他库,如 loadash 或 undersore。 I have to do it from nomal ES6 methods.
我必须通过普通的 ES6 方法来完成。
You can use the filter method.您可以使用过滤器方法。 Not sure how you used it, but this is how it should look.
不知道你是如何使用它的,但它应该是这样的。
sd.searchData.filter(obj => {
if (!obj.tags.industry.includes("i1"))
return false;
if (!obj.tags.portfolio.includes("p1"))
return false;
return true;
})
Or a one liner:或单班轮:
sd.searchData.filter(obj => obj.tags.industry.includes("i1") && obj.tags.portfolio.includes("p1"));
You could take an array with the search criteria and filter the array by taking the key and value for a check.您可以使用带有搜索条件的数组,并通过检查键和值来过滤数组。
var data = { searchData: [{ description: "ISU ISU", tags: { portfolio: ["p1", "p2", "p3"], industry: ["i1", "i2", "i3"] } }, { description: null, tags: { portfolio: ["p1", "p2", "p3"], industry: ["i1", "i4", "i5"] } }, { description: null, tags: { portfolio: ["p4", "p5", "p6"], industry: ["i1", "i2", "i3"] } }] }, search = [["portfolio", "p1"], ["industry", "i1"]], result = data.searchData.filter(({ tags }) => search.every(([k, v]) => tags[k].includes(v))); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
let sd = { searchData : [ { "description": "ISU ISU", "tags": { "portfolio": [ "p1", "p2", "p3" ], "industry": [ "i1", "i2", "i3" ] }, }, { "description": null, "tags": { "portfolio": [ "p1", "p2", "p3" ], "industry": [ "i1", "i4", "i5" ] }, }, { "description": null, "tags": { "portfolio": [ "p4", "p5", "p6" ], "industry": [ "i1", "i2", "i3" ] }, } ] }; console.log(sd.searchData.filter((element) => { return element.tags.portfolio.includes('p1') && element.tags.industry.includes('i1') }));
You can do:你可以做:
const sd = {searchData : [{"description": "ISU ISU","tags": {"portfolio": ["p1","p2","p3"],"industry": ["i1","i2","i3"]},},{"description": null,"tags": {"portfolio": ["p1","p2","p3"],"industry": ["i1","i4","i5"]},},{"description": null,"tags": {"portfolio": ["p4","p5","p6"],"industry": ["i1","i2","i3"]},}]}; const result = sd.searchData.filter(({tags}) => tags.industry.includes('i1') && tags.portfolio.includes('p1')); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.