FLUTTER JSON Filtering Data with Condition in Another Data

Dimas Satrya

I got stuck in this problem.

I have 2 JSON data here :

List<ProductModel> prdctList
data: [
    {
        "name": "product 1",
        "product_category": {
            "id": 1,
            "name": "Cat Food"
        }
    },
    {
        "name": "product 2",
        "product_category": {
            "id": 3,
            "name": "Accesories"
        }
    }
]


List<prdctCtgrModel> prdctCtgrList
data : [
    {
        "id": 1,
        "name": "Cat Food",
        "pet_type": [
            {
                "id": 1,
                "type": "Cat"
            }
        ]
    },
    {
        "id": 2,
        "name": "Dog Food",
        "pet_type": [
            {
                "id": 2,
                "type": "Dog"
            }
        ]
    },
    {
        "id": 3,
        "name": "Accesories",
        "pet_type": [
            {
                "id": 1,
                "type": "Cat"
            },
            {
                "id": 2,
                "type": "Dog"
            }
        ]
    }
]

I have a button to select pet_type, and the function I need is to filter product list with pet_type that I select. How to connect them with product_category from 2 data above?

example 1 :

  • I select pet_type 'Cat'
  • the result prdctList will be product 1 and product 2.
  • because product_category from product 1 and product 2 is having pet_type "Cat".

example 2 :

  • I select pet_type 'Dog'
  • the result prdctList will be only product 2.
  • because product_category from product 2 is having pet_type "Dog", but product 1 didn't.
Nguyen family

I don't quite understand but isn't your problem solved by using a loop?

for (int i = 0; i < data.length; i++) {
  List petTypes = data[i]["pet_type"].toList();
  for (int j = 0; j < petTypes.length; j++) {
    if (petTypes[j]["type"] == "Cat") {
      print(data[i]);
      // or do something, create new list
    }
  }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related