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. I want to filter the above with portfolio value of p1 and industry with i1.
I tried using filter but not able to get the required result. I cannot use other libraries like loadash or undersore. I have to do it from nomal ES6 methods.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.