Reputation: 1
is it correct syntax to use string literals inside if statements. please guide. how can i use categ dynamically in the function based on different values so that i dont have to write the same function for every button clicked.
const filterButtons= document.querySelectorAll(".filter-btn")
let categ;
filterButtons.forEach(function (btn) {
btn.addEventListener("click",function (e) {
if(e.currentTarget.dataset.id=="price") {
categ = "price";
console.log(categ);
}
if(e.currentTarget.dataset.id=="discountPercentage") {
categ = "discountPercentage";
console.log(categ);
}
if(e.currentTarget.dataset.id=="rating") {
categ = "rating";
console.log(categ);
}
let newModData = [...mainProducts];
let i=0;
let j=0;
let fixed = 0
while(j< newModData.length-1) {
while(i< newModData.length-1)
{
if(`newModData[i+1].${categ}`< `newModData[fixed].${categ}`)
{
const temp = Object.assign({}, newModData[fixed]);
newModData[fixed] = newModData[i+1];
newModData[i+1] = temp;
}
i++;
}
i=j+1;
fixed++;
j++;
}
displayNew(newModData);
})
is it correct syntax to use string literals inside if statements. please guide. how can i use categ dynamically in the function based on different values so that i dont have to write the same function for every button clicked.
Upvotes: -1
Views: 41
Reputation: 959
If newModData
is an array of objects, then the correct syntax is:
if(newModData[i+1][categ] < newModData[fixed][categ]) {
// Your logic here
}
To access properties of an object dynamically you must use brackets []
instead of dot .
:
const prop = "name"; //
const someObj = {
name: "Jane",
age: 20
}
console.log(someObj[prop]); // --> Jane
Upvotes: 1