Reputation: 1
I want to filter an object array taking into account multiple attribute
values. The attributes are selected using checkboxes, I want to filter the array using those values (for example, Ram
, Primary camera
).
I want to filter like an E-commerce website:
var myObject = [
{
"ProId": 12,
"ProName": "Samsung Galaxy A9",
"AttriValue": {
"Front Camera": "16 MP and Above",
"Internal Memory": "128 GB and Above",
"Network Type": "4G",
"Primary Camera": "16 MP and Above",
"Ram": "6 GB"
}
},
{
"ProId": 11,
"ProName": "Vivo Y95",
"AttriValue": {
"Front Camera": "16 MP and Above",
"Internal Memory": "64 GB",
"Network Type": "4G",
"Primary Camera": "13 - 15.9 MP",
"Ram": "4 GB"
}
},
{
"ProId": 10,
"ProName": "OPPO A7",
"AttriValue": {
"Front Camera": "16 MP and Above",
"Internal Me...
....
}
]
Upvotes: 0
Views: 615
Reputation: 886
You can use filter
for that:
const myObject = [{
"ProId": 12,
"ProName": "Samsung Galaxy A9",
"AttriValue": {
"Front Camera": "16 MP and Above",
"Internal Memory": "128 GB and Above",
"Network Type": "4G",
"Primary Camera": "16 MP and Above",
"Ram": "6 GB"
}
},
{
"ProId": 11,
"ProName": "Vivo Y95",
"AttriValue": {
"Front Camera": "16 MP and Above",
"Internal Memory": "64 GB",
"Network Type": "4G",
"Primary Camera": "13 - 15.9 MP",
"Ram": "4 GB"
}
},
]
const attrToFilter = {
"Primary Camera": "13 - 15.9 MP",
"Ram": "4 GB"
};
const filterFunction = (data, attrToFilter) =>
data.filter(e =>
Object.keys(attrToFilter)
.map(i =>
e.AttriValue[i] === attrToFilter[i]
)
.every(attr => !!attr)
)
console.log(filterFunction(myObject, attrToFilter))
EDIT
I've updated my code for filtering with dynamic attributes.
You can set the attributes to be filtered with in:
attrToFilter
Upvotes: 0
Reputation: 2908
1. Use Javascript filter method
filtered = myObject.filter(i => i.AttriValue.Ram === "4 Gb")
this way you can filter all products with 4GB ram
2. Iterate over myObject with for or while loop
filtered = []
for(let obj of myObject) {
if(obj.AttriValue.RAM === '4 GB') filtered.push(obj)
}
Upvotes: 1