0

I have this json file that fetch from API

const items =    [
    {
        "ID": 21,
        "Name": "New Town (Near Me)",
        "ShortDescption": "one · Another one · Another other one",
        "LongDescption": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \r\n\r\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \r\n\r\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
        "Thumbnail": "https://via.placeholder.com/110x110",
        "CoverImage": "https://via.placeholder.com/480x148",
        "OperatingHours": "somrthing",
        "FoodCategory": [
            {
                "ID": 2,
                "Name": "Halal"
            },
            {
                "ID": 7,
                "Name": "Vegetarian"
            },
            {
                "ID": 9,
                "Name": "Seafood"
            }
        ],
        "DeliveryCategory": [
            {
                "ID": 2,
                "Name": "Delivery"
            }
        ],
        "PhoneNo": "123123123123",
        "Address": "something",
        "MapsUrl": "#",
        "SiteUrl": "#",
        "Deals": null
    },
    {
        "ID": 23,
        "Name": "Old Town (Somewhere)",
        "ShortDescption": "one · Another one · Another other one",
        "LongDescption": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \r\n\r\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \r\n\r\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
        "Thumbnail": "https://via.placeholder.com/110x110",
        "CoverImage": "https://via.placeholder.com/480x148",
        "OperatingHours": "somrthing",
        "FoodCategory": [
            {
                "ID": 1,
                "Name": "Asian"
            },
            {
                "ID": 4,
                "Name": "Western"
            },
            {
                "ID": 8,
                "Name": "Bakeries"
            }
        ],
        "DeliveryCategory": [
            {
                "ID": 1,
                "Name": "Self-Pick up"
            },
            {
                "ID": 2,
                "Name": "Delivery"
            },
            {
                "ID": 3,
                "Name": "Pre-Order"
            },
            {
                "ID": 4,
                "Name": "Seng Problem"
            }
        ],
        "PhoneNo": "123123123123",
        "Address": "something",
        "MapsUrl": "#",
        "SiteUrl": "#",
        "Deals": [
            {
                "ID": 24,
                "Name": "Buy 1 Free 1000",
                "Promocode": "B1F1000"
            }
        ]
    },
    {
        "ID": 25,
        "Name": "Mid Town (Far Away)",
        "ShortDescption": "one · Another one · Another other one",
        "LongDescption": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \r\n\r\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \r\n\r\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
        "Thumbnail": "https://via.placeholder.com/110x110",
        "CoverImage": "https://via.placeholder.com/480x148",
        "OperatingHours": "somrthing",
        "FoodCategory": [
            {
                "ID": 1,
                "Name": "Asian"
            },
            {
                "ID": 3,
                "Name": "Dessert"
            }
        ],
        "DeliveryCategory": [
            {
                "ID": 3,
                "Name": "Pre-Order"
            },
            {
                "ID": 4,
                "Name": "Seng Problem"
            }
        ],
        "PhoneNo": "123123123123",
        "Address": "something",
        "MapsUrl": "#",
        "SiteUrl": "#",
        "Deals": [
            {
                "ID": 26,
                "Name": "Buy 1 Free 1",
                "Promocode": "B1F1"
            },
            {
                "ID": 27,
                "Name": "Buy 5 Free 10",
                "Promocode": "B5F10"
            }
        ]
    }]

The tasks that I need to complete are to filter this json by multiple FoodCategory options and multiple DeliveryCategory options.

Currently, I'm stuck and just managed to pull out one FoodCategory by hardcoded value by using the below code

<div class="food-cat" data-filter-food="Asian" data-filter-food-id="1">
  <a title="Asian">
    <div class="tags-box">
      <span class="icon-bowl-chopsticks-noodles"></span>
      <span class="tags-name">Asian</span>
    </div>
  </a>
</div>
<div class="food-cat" data-filter-food="Halal" data-filter-food-id="1">
  <a title="Halal">
    <div class="tags-box">
      <span class="icon-icon-halal-3"></span>
      <span class="tags-name">Halal</span>
    </div>
  </a>
</div>
let food = [] ;   
document.querySelectorAll('.food-cat').forEach(item => {
  item.addEventListener('click', event => {
    item.classList.toggle("active");
    addOrRemove(food, item.getAttribute('data-filter-food'))
    foodCategoryFilter(food);
  });
});

function addOrRemove(array, value) {
  console.log('here')
  var index = array.indexOf(value);
  if (index === -1) {
    array.push(value);
  } else {
    array.splice(index, 1);
  }
}

function foodCategoryFilter(category){
  let foodCategoryFiltered = items.filter(i => i.FoodCategory.some(c => c.Name.includes('Halal')))
}

Need help on how to meet the requirements and didn't required any changes on the API backend.

UPDATE I found one article: Filter array by finding multiple conditions in nested array of objects, so I changed my filter parameters to below

let filters = {
  FoodCategory: ['Asian', 'Dessert'],
  DeliveryCategory: ["Pre-Order"]
}

and my filter code like below

function foodCategoryFilter(obj){

  const foodCategoryFiltered = items.reduce((acc, item) => {
    item.FoodCategory = item.FoodCategory.filter(f => (
      obj.FoodCategory.every(ai => item.FoodCategory.map(i => i.Name).includes(ai))
    ))
  
    let itemCount = item.FoodCategory.length
    console.log(itemCount)
    if (itemCount > 0) {
      acc.push(item)
    }
  


}

console.log(foodCategoryFilter(filters))

Finally it can filter by FoodCategory but now I want to expand this filter to also include filter the restaurant by DeliveryCategory. Need help on this

4
  • What is the category parameter supposed to be? Commented Jun 21, 2022 at 8:46
  • @Barmar it will be an object ['Halal', 'Asian'] Commented Jun 21, 2022 at 12:03
  • Isn't that the food array? Commented Jun 21, 2022 at 13:27
  • @Barmar oh yes, sorry my mistake. its an array Commented Jun 22, 2022 at 1:55

1 Answer 1

0

Assuming category is an array like food:

function foodCategoryFilter(category) {
  return items.filter(i => i.FoodCategory.some(fc => category.includes(fc.name)))
Sign up to request clarification or add additional context in comments.

3 Comments

It gave me some output but the problem now, is when I choose Halal and Asian categories together it will show all items instead of empty as there is no restaurants in the json with both food category
If you want it to match all categories use .every() instead of .some().
I used .some() because your code just checks if (itemcount > 0), which will be true if it matches any of the categories, not all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.