Reputation:
I have an array containing a number of items (below), my aim is to be able to use a search bar to search for an item or items matching a keyword for it and then generate a list of matching products in html to display them
const catalog = {
"Ipad": {
"name": "Ipad",
"key": "ipad",
"keywords": ["tablet", "apple"],
"price": 800
},
"Iphone": {
"name": "Iphone",
"key": "iphone",
"keywords": ["apple", "phone"],
"price": 1200
},
"GalaxyTablet": {
"name": "GalaxyTablet",
"key": "galaxytablet",
"keywords": ["galaxy", "tablet", "samsung"],
"price": 800
},
"GalaxyPhone": {
"name": "GalaxyPhone",
"key": "galaxyphone",
"keywords": ["galaxy", "phone", "samsung"],
"price": 1000
},
"HTCPhone": {
"name": "HTCPhone",
"key": "htcphone",
"keywords": ["htc", "phone"],
"price": 650
},
"SonyPhone": {
"name": "SonyPhone",
"key": "sonyphone",
"keywords": ["sony", "phone"],
"price": 850
},
"WindowsPhone": {
"name": "WindowsPhone",
"key": "windowsphone",
"keywords": ["phone", "windows"],
"price": 800
},
};
Upvotes: 0
Views: 43
Reputation: 1568
You need to iterate each object from your data and filtered it out by search keyword as shown in below code.
const catalog = {
"Ipad": {
"name": "Ipad",
"key": "ipad",
"keywords": ["tablet", "apple"],
"price": 800
},
"Iphone": {
"name": "Iphone",
"key": "iphone",
"keywords": ["apple", "phone"],
"price": 1200
},
"GalaxyTablet": {
"name": "GalaxyTablet",
"key": "galaxytablet",
"keywords": ["galaxy", "tablet", "samsung"],
"price": 800
},
"GalaxyPhone": {
"name": "GalaxyPhone",
"key": "galaxyphone",
"keywords": ["galaxy", "phone", "samsung"],
"price": 1000
},
"HTCPhone": {
"name": "HTCPhone",
"key": "htcphone",
"keywords": ["htc", "phone"],
"price": 650
},
"SonyPhone": {
"name": "SonyPhone",
"key": "sonyphone",
"keywords": ["sony", "phone"],
"price": 850
},
"WindowsPhone": {
"name": "WindowsPhone",
"key": "windowsphone",
"keywords": ["phone", "windows"],
"price": 800
},
};
const searchKeyword = 'apple';
const finalResult = []
for (const items in catalog) {
const obj = catalog[items];
if (obj.keywords.indexOf(searchKeyword) != -1) {
finalResult.push(obj);
}
}
console.log(finalResult);
Upvotes: 1