sorry for my English at the start. I have a problem with filtering a list of products posted in JSON. The code is written in react native with the use of react redux.
The object of each product looks like this:
ProductTest {
"barcode": "barcode",
"brand": "brand",
"category": "category",
"description": "description",
"details": "details",
"filters": Object {
"cienkie": false,
"farbowane": false,
"krecone_i_puszczace": false,
"normalne": false,
"oslabione": false,
"przetluszczajace": false,
"suche_i_zniszczone": false,
"wszystkie": true,
},
"id": "0",
"image": "image",
"ingredients": "ingredients",
"name": "name",
},
And the "appliedFilters" list looks like this:
Object {
"cienkie": false,
"farbowane": false,
"krecone_i_puszczace": false,
"normalne": false,
"oslabione": false,
"przetluszczajace": false,
"suche_i_zniszczone": false,
"wszystkie": false,
}
I don't know how to make the "appliedFilters" list to be compared with the "filters" for each product, and to return the matching products from the list. If you have any ideas I would be greatful.
You can use the array filter method :
let keys = Object.keys(appliedFilters);
let filteredList = productList.filter(product => {
let matching = true;
keys.forEach(key => {
if(product.hasOwnProperty(key)){
if(!(product.filters[key] === appliedFilters[key])) matching = false;
}
}
if(matching) return product;
})
If you are sure that the attributes order of the filter and the product objects will not change, you can simplify like this :
let filteredList = productList.filter(product => JSON.stringify(product.filters) === JSON.stringify(appliedFilters))