skip to Main Content

I am trying to implement a search function where I search through all values in a JSON object without knowing the keys beforehand.

It goes something like this:

object.where((o) => o['name'].contains(searchString))

but notice that I have to specify the key ‘name’ to search through this part of the JSON. I want to be able to search through the entire JSON object and I don’t know what the keys would be ahead of time.

Is there a way to do this?

2

Answers


  1. If I understand you correctly, what you need is only traversing all values:

    bool check(o) {
      final values = o.values;
      for (final value in values) {
        if (value.contains(searchString) {
          return true;
        }
      }
      return false;
    }
    
    object.where((o) => check(o)).toList()
    
    Login or Signup to reply.
  2. Another approach could be

    void main() {
      List<Map<String, dynamic>> objects = [
        {'name': 'John Doe', 'age': 25},
        {'name': 'Jane Smith', 'age': 30},
        {'name': 'Alice Wonderland', 'age': 22},
      ];
    
      String searchString = 'Doe';
    
      // Filter the list of maps based on the 'name' containing the searchString
      List<Map<String, dynamic>> filteredList = objects
          .where((map) => map['name'].toString().contains(searchString))
          .toList();
    
      // Print the filtered list
      print(filteredList);
    }
    

    but I’m not sure about the structure of your map

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search