Home > front end >  Filter nested objects in a list in Flutter and get the values of filtered object
Filter nested objects in a list in Flutter and get the values of filtered object

Time:04-08

I have a List of objects which I want to filter and get the value of a key based on the filtered list.

 class CategoryData({
    String name,
    List<SubCategoryData> subCategories
  })


  const SubCategoryData({
    required String name,
    required String id,
 })

The data might look like this, I want to get the object for a matching key value:

  final list =  [{
        "categoryData": {
            "name": "Test123",
            "subCategories": [{
                "name": "Test123",
                "id": "Testid"
            }]
        }
    },
    {
        "categoryData": {
            "name": "Test456",
            "subCategories": [{
                "name": "**Test456**", //Get name for matching id below
                "id": "*Testid456*"
            }]
        }
    }
    ]

I want to get the value of the "name" key for matching "id" of subCategories

i.e, I want to get "Test456" for matching "Testid456".

I have tried following but it gives me the whole parent list which is not very helpful.

final getFilteredList = list
        .where((content) =>
            content.subCategories.any((tag) => tag.id == 'Testid456'))
        .toList();

CodePudding user response:

Do something like this in dart. convert python to dart

name="Test456"
for x in data:
    if x['categoryData']['name'] == name:
        print(x)

CodePudding user response:

You can try the code below

String result = searchFromId(searchId, categoryDataList);
print(res);
String searchFromId(String searchId, List<CategoryData> catDataList) {
  return catDataList
      .where((e) =>
          e.subCatData
              .firstWhere((d) => d.id == searchId,
                  orElse: () => SubCategoryData("", ""))
              .id !=
          "")
      .first
      .name;
}

If you want to have a list of names use .map() along with .where(). Like below

List<String> searchFromId(String searchId, List<CategoryData> catDataList) {
  return catDataList
      .where((e) =>
          e.subCatData
              .firstWhere((d) => d.id == searchId,
                  orElse: () => SubCategoryData("", ""))
              .id !=
          "").map((e)=>e.name).toList();
}
  • Related